0

我在 viewModel 中保留时间状态,需要将当前状态存储在首选项中,并在用户关闭并再次打开应用程序时再次加载时间状态。这是我当前的代码。

视图模型

class TimeViewModel(): ViewModel(){
 private val _time = MutableLiveData<Long>()
 val time: LiveData<Long> = _time
 fun onTimeChange(newTime: Long) {
   _time.value = newTime
 }
}

可组合功能

@Composable
fun Timer(timeViewModel:TimeViewModel = viewModel()){

 LaunchedEffect(key1 = time ){
  delay(1000L)
  timeViewModel.onTimeChange(time + 1)
 }
 val time: Long by timeViewModel.time.observeAsState(0L)
 val dec = DecimalFormat("00")
 val min = time / 60
 val sec = time % 60
 Text(
  text = dec.format(min) + ":" + dec.format(sec),
  style = MaterialTheme.typography.body1
 )
}
4

1 回答 1

0

尝试使用 dagger 进行依赖注入,您可以通过这种方式在您的商店中创建一个单例:

@Module
@InstallIn(SingletonComponent::class)
object MyModule {

    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "preferences")

    @Singleton
    @Provides
    fun provideDataStore(@ApplicationContext app: Context ) :  DataStore<Preferences> = app.dataStore
}

然后只需注入您的视图模型并使用它!

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val dataStore: DataStore<Preferences>
) : ViewModel() {

    private val myKey = stringPreferencesKey("USER_KEY")// init your key identifier here

    fun mySuperCoolWrite(){
        viewModelScope.launch {
            dataStore.edit {
                it[myKey] = body.auth
            }
        }
    }

    fun mySuperCoolRead(){
        viewModelScope.launch {
            val preferences = dataStore.data.first()
            preferences[myKey]?.let {
                // here access your stored value with "it"
            }
        }
    }

}

或者只是注入你的控制器构造函数

@ApplicationContext app: Context

在这里你可以找到更多信息

于 2022-02-01T23:54:09.337 回答