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

相关内容

热门资讯

免费测试版!老友跑得快辅助小说... 免费测试版!老友跑得快辅助小说最新章节,广西老友玩有破解码,详细教程(有挂教学)运老友跑得快辅助小说...
专业讨论!边锋老友杰克辅助,甘... 专业讨论!边锋老友杰克辅助,甘肃胡乐白银辅助,详细插件(有挂方略)甘肃胡乐白银辅助是不是有人用挂微扑...
科技揭秘!hhpoker作笔实... 科技揭秘!hhpoker作笔实战视频,赣牌圈破解器,详细工具(真实有挂)1、完成hhpoker作笔实...
避坑细节!四川长牌皮皮游戏挂,... 避坑细节!四川长牌皮皮游戏挂,微信雀神挂件开挂辅助,详细插件(有挂细节)微信雀神挂件开挂辅助脚本下载...
玩家亲测!博乐填大坑有没有bu... 玩家亲测!博乐填大坑有没有buff,微友辅助神器下载,详细攻略(有挂解惑)1、起透看视 博乐填大坑有...
必备教程!微乐小程序卡五星脚本... 必备教程!微乐小程序卡五星脚本,新超圣辅助靠谱不,详细脚本(新版有挂)1、全新机制【微乐小程序卡五星...
一起来讨论!哥哥打大a辅助神器... 一起来讨论!哥哥打大a辅助神器,钱柜手游辅助,详细技巧(果真有挂)1、哥哥打大a辅助神器免费脚本咨询...
每日必看推荐!青鸟辅助器,hh... 每日必看推荐!青鸟辅助器,hh poker有没有辅助软件,详细器(有挂辅助)1、hh poker有没...
实操分享!胡乐胡乐辅助脚本可靠... 实操分享!胡乐胡乐辅助脚本可靠吗,wepokerplus辅助作弊,详细app(有挂猫腻)1、让任何用...
记者爆料!丽水茶苑手机辅助,蜀... 记者爆料!丽水茶苑手机辅助,蜀山四川游戏修改工具,详细工具(有挂教程)1、操作简单,无需蜀山四川游戏...