Observable runs on main thread even though subscribeOn() is called on another thread

后端 未结 1 817
独厮守ぢ
独厮守ぢ 2020-12-23 14:42

I got a weird issue in one of my activities. When coming back from taking a picture / video, in my onActivityResult I am showing a dialog that lets the user na

相关标签:
1条回答
  • 2020-12-23 15:17

    subscribeOn and observeOn is the mostly confused operators there are. The former makes sure that subscription side effects happen on the specified scheduler (thread), but that doesn't mean that values will pop up on that thread as well.

    For example, if your Observer opens a network connection when one subscribes to it, you don't want that to run on the main thread, therefore, you need subscribeOn to specify where that subscription and thus the network connection will be created.

    When data finally arrives, the emitting thread can be anything, one of the schedulers or a background plain old thread. Since we don't know or don't like that thread, we want to move the observation of the data to another thread. This is what observeOn does: makes sure operators after it will execute their onNext logic on the specified scheduler. Android devs use it already to move the observation of values back to the main thread.

    What's rarely explained though is what happens when you want some extra computation off the main thread before the final result lands on the main thread again: use multiple observeOn operators:

    source
    .observeOn(Schedulers.computation())
    .map(v -> heavyCalculation(v))
    .observeOn(Schedulers.io())
    .doOnNext(v -> { saveToDB(v); })
    .observeOn(AndroidSchedulers.mainThread())
    ...
    
    0 讨论(0)
提交回复
热议问题