I have some expensive operations that only need to be performed once (e.g. load/ download large files, load large ML models, or calculate optimized data structure based on some other data). I want to use this for every value the Observable/ Flowable generates:
The following code works, but it runs heavyProcessing()
and heavyProcessing2()
on the caller's thread. In my case, I can't choose what my callers thread (its the main
thread because I am using WorkManager's RxWorker, which calls createWork from main
). Therefore, start
blocks the main thread. How do I get heavyProcessing
to be performed in the background with RxJava and also available to the subsequent RxJava chain?
fun start(): Observable<Unit> {
val heavy = heavyProcessing() // the heavy value i want to use everywhere!
val anotherHeavyObject = heavyProcessing2()
val items = Observable.fromIterable(listOfHundredsOfItems)
.map { doSomeWork(it, heavy) }
.map { doSomeWork(it, anotherHeavyObject) }
}
My attempts has so far not worked:
- Create a wrapper around the existing function: The issue with this code is the Observable returned by
start()
does not get observed, so thedoSomeWork
doesn't actually get done. I only know this because I put breakpoints in atdoSomeWork
, and it never gets called.
fun startInBackground(): Single<Unit> {
return Single.fromCallable {
start()
}
}
- I've been trying to find ways of 'unnesting' the inner
Observable
(inside theSingle
), as that's probably the issue here. The innerObservable
is not being observed.
This RxJava stuff is very unintuitive even after reading the guide