I have a state flow that emits a value once the HTTP request is returned with the response, the value will be shown as a list in Activity, I'm using Kotlin coroutines StateFlow
for communication between the ViewModel and Activity.
I'm using androidx
lifecycle repeatOnLifecycle
function like this:
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.successFlow.collect { binding.recyclerView.adapter = ExampleAdapter(it) }
}
}
This is working fine at the beginning but then I realized that every time the user goes to another screen and back to the previous screen the state flow will reemit the value which in this case will lose the list state, for example, if the user scrolled to item 10
in the list and then goes to another screen and return back the list will scroll to position 0
because the setAdapter
method invoked again, which is not the case when using LiveData
.
Now I need to handle StateFlow
state and configuration state too, I tried to use the distinctUntilChanged
method but as the documentation says Applying 'distinctUntilChanged' to StateFlow has no effect
.
The question here how I can achieve the same LiveData
behaviour using StateFlow
.