I would like to do some heavy lifting in the background thread of my iOS app and NOT freeze the UI while it is being performed. What I try is:
self.someDisposable = heavyLiftingFuncReturningObservable()
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.observeOn(MainScheduler.instance)
.subscribe(
onNext: { [weak self] image in
// update UI
},
onError: { ... }
)
Why does the above not work as expected and how to make it work?
I believe the problem lies in your implementation of .heavyLiftingFuncReturningObservable(), namely in the fact that apparently it starts working on current thread instead of waiting until being subscribed to and running on background scheduler. Solution for that is to use .deferred() inside of .heavyLiftingFuncReturningObservable() function.
See http://adamborek.com/top-7-rxswift-mistakes/
You can do this:
self.someDisposable = Observable.just(0) // dummy
.observeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.flatMap { [unowned self] _ in
heavyLiftingFuncReturningObservable()
}
.observeOn(MainScheduler.instance)
.subscribe(
onNext: { [weak self] image in
// update UI
},
onError: { ... }
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With