要在ViewModel
中使用DataStore
个首选项,您需要创建一个ViewModel
来获取和更新首选项,有点像Ethan Denvir中的"Android Compose DataStore Tutorial ".
class PreferencesViewModel(application: Application) : AndroidViewModel(application) {
private val dataStore: DataStore<Preferences> = application.dataStore
// LiveData to expose the account type from DataStore
private val _accountType = MutableLiveData<String>()
val accountType: LiveData<String> = _accountType
init {
viewModelScope.launch {
fetchAccountType()
}
}
private suspend fun fetchAccountType() {
dataStore.data.map { preferences ->
preferences[ACCOUNT_TYPE] ?: ""
}.collect { accountTypeValue ->
_accountType.postValue(accountTypeValue)
}
}
// Function to update account type in DataStore
fun updateAccountType(newAccountType: String) {
viewModelScope.launch {
dataStore.edit { preferences ->
preferences[ACCOUNT_TYPE] = newAccountType
}
}
}
}
要访问composable function中的PreferencesViewModel
,可以使用viewModel()
Composable(与this example中的一样)来获取ViewModel
和observeAsState()
的实例,以观察Composable中的LiveData As状态.
@Composable
fun PreferencesScreen(preferencesViewModel: PreferencesViewModel = viewModel()) {
val accountType by preferencesViewModel.accountType.observeAsState("")
Column {
Text(text = "Account Type: $accountType")
Button(onClick = {
preferencesViewModel.updateAccountType("NewAccountType")
}) {
Text("Update Account Type")
}
}
}
对于处理Retrofit HTTP请求,可以使用类似的ViewModel
方法,其中ViewModel
将处理作出网络请求并相应地更新UI状态.
我在该代码中有一个错误:我在Composable函数中得到一个未解决的引用错误observeAsState
,但我不确定原因.任何进一步的指导都将不胜感激.
首先,确保将Jetpack Compose LiveData integration library添加到模块的build.gradle
文件中.如果缺少它,则需要添加它.:
dependencies {
implementation "androidx.compose.runtime:runtime-livedata:<compose_version>"
}
将<compose_version>
替换为您正在使用的Compose版本.确保所有与编写相关的依赖项使用相同的版本,以避免兼容性问题.
在使用observeAsState
的Kotlin文件中,确保具有以下IMPORT语句:
import androidx.compose.runtime.livedata.observeAsState