LiveData is not re-emitting when fragment is resumed

1.2k views Asked by At

In my fragment, I have this code:

fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    //...
    viewModel.state.observe(viewLifecycleOwner) {
        //do something
    }
}

And in my ViewModel:

class MyViewModel: ViewModel() {

    val state = liveData {
        val state = dataSource.getState()
        emit(state)
   }

}

When I navigate to another fragment or activity, and press back button, Fragment's onCreateView and onViewCreated methods are called, but viewModel.state has the same value. I mean, dataSource.getState() is not called again. I need state to be re-fetched from data source.

Is this possible using liveData builder? If not, how should I do it?

1

There are 1 answers

1
i30mb1 On BEST ANSWER

You need just cal load function every time when it needed. One of possible way to do it

ViewModel :

val stateLiveData = MutableLiveData<>()
    fun loadData() {
        viewModelScope.launch {
            val state = dataSource.getState()
            stateLiveData.setValue(state)
        }
    }

Fragment :

fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    //...
    viewModel.loadData()
    viewModel.stateLiveData.observe(viewLifecycleOwner) {
        //do something
    }
}