1

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{}?

Sam Chen
  • 7,597
  • 2
  • 40
  • 73

1 Answers1

0

Official documentation points out it should look like this:

private val _country = MutableStateFlow<List<String>>("")
val country: StateFlow<List<String>> = _country

where _country you use for update value and country to refer for reading to the rest application (to consumers)

The issue is you could not use StateFlow<> type for two-way bindings, only for reading. At least I haven't found yet the way to operate it and keep MutableStateFlow<> encapsulated.

Just a remark to your code.

Joe Dow
  • 583
  • 1
  • 3
  • 12