Let me show a simplified example of the problem I'm struggling with:
class CarService {
func getCars() -> Single<[Car]> {
return Single.create { observer in
// Here we're using a thread that was defined in subscribeOn().
someCallbackToAPI { cars in
// Here we're using main thread, because of the someCallbackToAPI implementation.
observer(.success(cars))
}
}
}
}
class CarRepository {
func syncCars() -> Completable {
return CarService().getCars()
.flatMapCompletable { cars in
// Here we're using main thread, but we want some background thread.
saveCars(cars)
}
}
}
class CarViewController {
func loadCar() {
CarRepository().syncCars()
.subscribeOn(someBackgroundScheduler)
.observeOn(MainThread)
.subscribe()
}
}
From the bottom: CarViewController
wants to sync all the cars from some external API. It defines what thread should be used for the sync with subscribeOn
- we don't want to block the UI thread. Unfortunately, underneath, the CarService
has to use some external library methods (someCallbackToAPI
) that always returns the result in a main thread. The problem is that after receiving the result, all methods below like e.g. saveCars
are called in the same main thread. saveCars
may block the UI thread because it saves data to database. Of course I could add observeOn
between threads between CarService().getCars()
and flatMapCompletable
, but I want the CarRepository
to be dump and know nothing about the threads. It is the CarViewController
responsibility to define working thread.
So my question is, is it a way I could get the scheduler passed in subscribeOn
method and switch back to the scheduler after receiving the result from someCallbackToApi
?