Can a RxJava chain emit 2 items for a single event emission by its source observable?

26 Views Asked by At

I am trying to emit UI State based on an UIEvent. The UIEvent is a PublishSubject which feeds events into the following rx chain

private val speciesStateObservable:Observable<PokemonListViewState> = _uiEvents.observeOn(schedulers.io()).flatMap { uiEvent ->
    handleUIEvent(uiEvent)
}.scan(currentState) { previousState, newList ->
    val previousList = previousState.pokemonList as MutableList
    previousList.addAll(newList)
    Log.d("TAG", "${previousList.size}")
    previousState.copy(showLoading = false, pokemonList = previousList)
}.distinctUntilChanged().replay(1).doOnSubscribe {
    disposable.add(it)
}.doOnError {
    handleError(it)
}.doOnNext {
    //do some additional processing with this data
}

the handleUIEvent looks like this

    private fun handleUIEvent(uiEvent: UIEvent): Observable<List<PokemonSpecies>> {
    return when (uiEvent) {
        is UIEvent.FirstLoad -> fetchSpeciesUseCase.execute(currentPage).toObservable()
        is UIEvent.EndOfPage -> fetchSpeciesUseCase.execute(++currentPage).toObservable()
        is UIEvent.ItemClick -> Observable.just(currentState.pokemonList)
    }
}

this function makes the api call to fetch some data.

Now, for every UIEvent, I want the speciesStateObservable:Observable<PokemonListViewState> to emit a loading state first while the background fetching operation is in progress, and then emit the result state once the background operation is complete.

My state holder is

data class PokemonListViewState(val showLoading: Boolean, val pokemonList: List<PokemonSpecies>)

TL;DR

I want to emit 2 items for every one emission from source observable. First one being the loading state PokemonListViewState(loading = true, items = mutableListOf()) and second is the result state PokemonListViewState(loading = false, items = listofitems)

scan operator didn't help because it emits the initial state without executing the background operation inside flatMap, and I don't want to update the state inside doOnNext because i don't want to break the chain. Please help!!

0

There are 0 best solutions below