刚学MutableStateFlow
,想换MutableLiveData
。另外Android不建议我们LiveData
在里面观察ViewModel
(除非你用过observeForever(observer)
但是你要记得把它去掉,这样有点麻烦)。
data class Student(var id: Long, var name: String, var countryIndex: Int)
class FirstViewModel(application: Application) : AndroidViewModel(application) {
val uiScope = viewModelScope //Main Dispatcher
val countries = listOf("China", "America", "Japan", "Korea")
val student = Student(0, "Kate", 2) //faking database object
val country = MutableStateFlow(countries[student.countryIndex]) //two-way bind with AutoCompleteTextView "text" attribute
init {
observeCountry()
}
private fun observeCountry() = uiScope.launch { //<- should move to other Dispatcher??
country.collect { country ->
countries.indexOf(country).let { student.countryIndex = it } //country name -> country index -> update Student object
}
}
}
上面的代码工作得很好,但我想确保我MutableStateFlow
在这个例子中是否正确使用。我需要切换到Dispatchers.Default
吗collect{}
?