Search code examples
androidkotlinrx-javarx-java2rx-kotlin2

Perform non-transformative action on each item in observable before onNext


I've attached a function can be called from multiple viewModels, I'm trying to store each "restaurant" to the DB in a central function before returning this observable to a viewModel.

I'm new to rxandroid and I'm wondering if there is a way to perform a non-transformative and non-consuming action on each item before the final onNext() in subscribe().

(Something like doOnEach() below):

fun getData() : CompositeDisposable {
        return apiProvider!!.loadRestaurants()
            .flatMap { response : RestaurantOuterResponse? -> Observable.fromArray(
                response!!.restaurants
            )}
            .doOnEach() { restaurant : Restaurant ->
                ADBConnection.storeRestaurant(restaurant)
            }
    }

Two Solutions I've found so far was to:

  1. Have a function inside RestaurantOuterResponse to save all the values when the list of "Restaurants" is extracted in flatMap().
  2. Call the ADBConnection.storeRestaurant(restaurant) in onNext() in each individual viewModel.

None of these are great solutions, is what I suggested in the right direction? Or is there a better way?


Solution

  • You want doOnNext. (You were very close with "doOnEach")

    doOnNext is for side-effects within the stream and does not consume the item.

    See this question for more details about doOnNext.