我有两个活动,A和B,我更新一个实时数据值并将其存储在B中的DataStore中,当我返回A时,它将不会更新。
DataStore类;
const val PREF_NAME = "com.family_locator.panic_button.pref_name"
class DataStoreRepository(context: Context) {
private object PreferenceKeys {
val panicButtonMessage = preferencesKey<String>("panicButtonMessage")
}
private val dataStore: DataStore<Preferences> = context.createDataStore(name
= PREF_NAME)
suspend fun savePanicButtonMessage(message: String) {
dataStore.edit { preferences ->
preferences[panicButtonMessage] = message
}
}
val readPanicButtonMessage: Flow<String> = dataStore.data
.catch { exception ->
if (exception is IOException) {
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preferences ->
val panicButtonMessage =
preferences[panicButtonMessage] ?:
context.getString(R.string.panic_message)
panicButtonMessage
}
}
我的ViewModel;
class PanicButtonViewModel(application: Application) : AndroidViewModel(application) {
private val dataStoreRepository = DataStoreRepository(application)
val readPanicButtonMessage = dataStoreRepository.readPanicButtonMessage.asLiveData()
fun savePanicButtonMessage(message: String) {
viewModelScope.launch(Dispatchers.IO) {
dataStoreRepository.savePanicButtonMessage(message)
}
}
}
和活动A;
viewModel = ViewModelProvider(this).get(PanicButtonViewModel::class.java)
viewModel.readPanicButtonMessage.observe(this, {
logMessage("alert message: $it")
text_message.text = it
})
当我重新启动应用程序时,它将被更新。
答案 0 :(得分:0)
尝试在class DataStoreRepository(context: Context) {
中创建Application.onCreate()
实例
class CustomApplication: Application() {
lateinit var dataStoreRepository: DataStoreRepository
private set
override fun onCreate() {
super.onCreate()
val dataStore: DataStore<Preferences> = createDataStore(name = PREF_NAME)
dataStoreRepository = DataStoreRepository(dataStore)
}
}
class DataStoreRepository(private val dataStore: DataStore<Preferences>) {
现在您可以做
class PanicButtonViewModel(application: Application) : AndroidViewModel(application) {
private val dataStoreRepository = (application as CustomApplication).dataStoreRepository