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、上手...
外挂机巧!哈糖大菠萝有没有挂,... 外挂机巧!哈糖大菠萝有没有挂,智星德州可以透视吗-确实存在有辅助app(哔哩哔哩)1、哈糖大菠萝有没...
外挂窍门!德普之星app安卓版... 外挂窍门!德普之星app安卓版破解版,竞技联盟透视插件-一贯一直总是有辅助教程(哔哩哔哩)1、竞技联...
外挂窍门!fishpoker透... 外挂窍门!fishpoker透视底牌,德州辅助工具到底怎么样-本来存在有辅助技巧(哔哩哔哩)一、德州...
外挂法门!聚星ai辅助工具收费... 外挂法门!聚星ai辅助工具收费多少,德普之星透视辅助插件-本来真的是有辅助软件(哔哩哔哩)外挂法门!...
外挂教材!德普之星私人局透视,... 外挂教材!德普之星私人局透视,大菠萝辅助器-都是真的有辅助工具(哔哩哔哩)运大菠萝辅助器辅助工具,进...
外挂讲义!德普之星有透视辅助吗... 外挂讲义!德普之星有透视辅助吗,aa poker辅助-果然真的有辅助教程(哔哩哔哩)进入游戏-大厅左...
外挂模块!哈糖大菠萝可以开挂吗... 您好,哈糖大菠萝可以开挂吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
外挂积累!佛手在线大菠萝辅助,... 外挂积累!佛手在线大菠萝辅助,德州透视是真的假的-总是一直总是有辅助软件(哔哩哔哩)1、首先打开德州...
外挂总结!德普之星有辅助软件吗... 外挂总结!德普之星有辅助软件吗,fishpoker透视-一贯是真的有辅助神器(哔哩哔哩)fishpo...