0

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
    }
Petermonteer
  • 296
  • 4
  • 17

1 Answers1

-2

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() }
            }
    }
Petermonteer
  • 296
  • 4
  • 17