AndroidPreferencesDataStoreFlowDoesn'tEmitSameValue
创始人
2024-10-09 14:01:50
0

可以通过以下代码示例解决此问题:

  1. 创建一个包含DataStore的viewmodel

class MyViewModel(application: Application) : AndroidViewModel(application) {

// Initialize DataStore
private val dataStore = application.applicationContext.createDataStore(
    name = "my_preferences"
)

// Get the preference value from DataStore
val myPreferenceFlow: Flow = dataStore.data
    .catch { exception ->
        // DataStore throws an exception if an error occurs
        if (exception is IOException) {
            emit(emptyPreferences())
        } else {
            throw exception
        }
    }
    .map { preferences ->
        preferences[MY_PREFERENCE_KEY] ?: ""
    }

}

  1. 在Activity/Fragment中使用此viewmodel并观察值变化

class MyActivity : AppCompatActivity() {

private lateinit var viewModel: MyViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.my_activity)

    // Initialize viewModel
    viewModel = ViewModelProvider(this).get(MyViewModel::class.java)

    // Observe the changes in myPreferenceFlow
    lifecycleScope.launch {
        viewModel.myPreferenceFlow.collect { value ->
            // Do something with the value
            Log.d("MyPreference", "Value = $value")
        }
    }
}

}

这样就可以获得DataStore的动态更新值并且不会遇到“Android Preferences DataStore Flow Doesn't Emit Same Value”的问题。

相关内容

热门资讯

透视详情"德普之星透... 透视详情"德普之星透视"其实有辅助工具(哔哩哔哩)1、德普之星透视免费脚本咨询教程、德普之星透视免费...
透视了解"hhpok... 透视了解"hhpoker德州牛仔视频"其实真的有辅助挂(哔哩哔哩)运hhpoker德州牛仔视频辅助工...
透视关于"aapok... 透视关于"aapoker ai插件"总是真的有辅助app(哔哩哔哩)1、玩家可以在aapoker a...
透视了解"wepok... 透视了解"wepoker透视脚本免费app"总是真的是有辅助脚本(哔哩哔哩)亲,关键说明,wepok...
透视详细"we-po... 透视详细"we-poker辅助"本来是有辅助插件(哔哩哔哩)1、进入游戏-大厅左侧-新手福利-激活码...
透视开挂"wepok... 透视开挂"wepoker私人局辅助"竟然真的有辅助插件(哔哩哔哩)1、wepoker私人局辅助免费辅...
透视辅助"poker... 透视辅助"pokerrrr2辅助"都是存在有辅助挂(哔哩哔哩)1、上手简单,内置详细流程视频教学,新...
透视透视"大菠萝78... 透视透视"大菠萝789辅助器下载"本来是真的辅助教程(哔哩哔哩)1、大菠萝789辅助器下载模拟器是什...
透视关于"hhpok... 透视关于"hhpoker脚本下载"本来存在有辅助app(哔哩哔哩)1、hhpoker脚本下载脚本辅助...
透视分享"wpk透视... 透视分享"wpk透视是真的吗"其实是真的辅助挂(哔哩哔哩)1、wpk透视是真的吗有没有辅助教程、wp...