'Android Paging Library 3 - Getting error "Attempt to collect twice from pageEventFlow..." when navigating back to a fragment
In my fragment I'm observing changes to a MutableLiveData stored in a viewModel.
Fragment:
viewModel.list.observe(viewLifecycleOwner) {adapter.submitData(lifecycle, it)}
This code is inside onCreateView
ViewModel:
var list: MutableLiveData<PagingData<Item>> = MutableLiveData()
When I switch to another fragment and return to this one I get the following error:
java.lang.IllegalStateException: Attempt to collect twice from pageEventFlow, which is an illegal operation. Did you forget to call Flow<PagingData<*>>.cachedIn(coroutineScope)
I'm using RxJava, and my repository returns an object of type Observable<PagingData<Item>> to my viewModel, that then subscribes to it and posts a value to the MutableLiveData.
getPagerObservable
.subscribeOn(io)
.observeOn(main)
.subscribe(::onSuccess, ::onError)
.addTo(compositeDisposable)
private fun onSuccess(list: PagingData<Item>){
list.postValue(list)
state.value = State.Success
}
Solution 1:[1]
I fixed it by passing viewModelScope to my UseCase (getPagerObservable above) and caching it there like so:
//GetPagerObservable UseCase
operator fun invoke(scope: CoroutineScope): Observable<PagingData<Item>> {
return repository.getObservable()
.cachedIn(scope)
.map { data ->
data.filter { it.isNotEmpty() }
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Petermonteer |
