1

I have this specific issue for which I cannot find a clean solution.

Observable.interval(1, TimeUnit.SECONDS)
    .flatMap { constructData() }
    .subscribe { data ->
        api.syncData(data)
            .repeat()
            .subscribe { response ->
                deleteSyncedData(data)
            }
    }

So as you can see from the code I need to construct some data package to send it to the backend and after it is correctly sent I'm deleting it from my local storage system. Right now it's working but looks a little bit like callback hell - what if I wanted to combine response with data and then make a request?

Does anyone see a better solution for this kind of operation?

Additionally I'd like to know how to switch between schedulers between those operations? I want to execute constructData() and deleteSyncedData() on Schedulers.computation() but api.syncData(data) on Schedulers.io().

Ernest Zamelczyk
  • 2,562
  • 2
  • 18
  • 32

1 Answers1

0

From the Rx doc for SubscribeOn:

You cannot use subscribeOn() multiple times in your chain. Technically, you can do so, but that won’t have any additional effect. In your code, if you are chaining two different Schedulers using subscribeOn() only the one closed to the source observable will take its effect and nothing else.

But you can achieve the same using observeOn(). You can switch between multiple Schedulers using observeOn() and then finally observe the result on MainThread

Example:

Observable.interval(1, TimeUnit.SECONDS)
    .observeOn(Schedulers.computation())
    .flatMap { constructData() }
    .observeOn(Schedulers.io())
    .flatMap { data -> api.syncData(data).map { data } }
    .observeOn(Schedulers.computation())
    .flatMap { data -> deleteSyncedData(data) }
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe { data ->

    }

But in my opinion this is also fine.

Observable.interval(1, TimeUnit.SECONDS)
    .flatMap { constructData() }
    .subscribe { data ->
        api.syncData(data)
            .repeat()
            .subscribe { response ->
                deleteSyncedData(data)
            }
    }
Prithvi Bhola
  • 3,041
  • 1
  • 16
  • 32