androidkotlinandroid-livedatakotlin-flow

How to migrate this from LiveData to Kotlin Flow on Android?


I'm new to Kotlin Flow on Android. Can you please tell me how I can migrate this LiveData code to Flow?

class MyViewModel @Inject constructor(private val myRepository: MyRepository) : ViewModel() {
    val myData = MutableLiveData<Data?>(null)
    fun fetchData(query: String) {
        viewModelScope.launch(Dispatchers.IO) {
            myData.postValue(myRepository.fetchSuspend(query))
        }
    }
}

Solution

  • You have to use a MutableStateFlow instead of MutableLiveData to hold the data. A StateFlow is similar to a LiveData in that it emits updates to its observers.

    class MyViewModel @Inject constructor(private val myRepository: MyRepository) : ViewModel() {
        private val _myData = MutableStateFlow<Data?>(null)
        val myData: StateFlow<Data?> 
            get() = _myData.asStateFlow()
    
        fun fetchData(query: String) {
            viewModelScope.launch(Dispatchers.IO) {
                _myData.value = myRepository.fetchSuspend(query)
            }
        }
    }