可以通过以下代码示例解决此问题:
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] ?: ""
}
}
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”的问题。