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”的问题。

相关内容

热门资讯

透视透明!uupoker透视,... 透视透明!uupoker透视,wepoker有辅助吗(辅助挂)详细开挂辅助平台;打开点击测试直接进入...
透视好友!闲玩暗宝辅助软件,德... 透视好友!闲玩暗宝辅助软件,德州局hhpoker(辅助挂)详细开挂辅助神器;无需打开直接搜索微信(1...
透明新版!we-poker靠谱... 透明新版!we-poker靠谱吗,wepoker数据分析工具(辅助挂)详细开挂辅助软件 了解更多开挂...
透视真的!新蜜瓜大厅破解,智星... 透视真的!新蜜瓜大厅破解,智星菠萝有挂吗(辅助挂)详细开挂辅助器;无需打开直接搜索薇:1367043...
透视存在!创思维激k透视免费,... 透视存在!创思维激k透视免费,hhpoker透视方法(辅助挂)详细开挂辅助器;打开点击测试直接进入微...
透明有挂!菠萝辅助器1.3,w... 透明有挂!菠萝辅助器1.3,wepoker辅助器安装包定制(辅助挂)详细开挂辅助器1、下载安装好we...
透视好友!丽水都来辅助器,we... 您好:丽水都来辅助器这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特...
透视ai!微信小程序开心十三张... 微信小程序开心十三张攻略是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可...
透视脚本!微乐小程游戏破解器下... 透视脚本!微乐小程游戏破解器下载,wepoker如何设置透视(辅助挂)详细开挂辅助下载;无需打开直接...
透明有挂!wepoker轻量版... 透明有挂!wepoker轻量版透视,hhpoker破解工具(辅助挂)详细开挂辅助安装;无需打开直接搜...