Just learned MutableStateFlow
, trying to replace MutableLiveData
. Also Android doesn't recommend that we observe LiveData
inside ViewModel
(unless you use observeForever(observer)
but you need to remember to remove it so it's kind of troublesome).
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
}
}
}
Above code works perfectly fine, but I want to make sure that whether I use MutableStateFlow
properly in this example. Do I need to switch to Dispatchers.Default
for the collect{}
?