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?
You need just cal load function every time when it needed. One of possible way to do it
ViewModel :
Fragment :