BlockingGet block UI thread RxJava 2

后端 未结 3 2024
[愿得一人]
[愿得一人] 2020-12-20 17:11

I am dealing with the problem.

I am trying to call RxJava in the sync manner, however doing that results in blocking the Main thread.

Here is my code

3条回答
  •  自闭症患者
    2020-12-20 17:54

    TL;TR

    never use observeOn(AndroidSchedulers.mainThread()) with blockingGet()


    Long version

    The output for:

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val result =
                    Single.just("Hello")
                    .subscribeOn(Schedulers.io())
                   // .observeOn(AndroidSchedulers.mainThread())
                    .map {
                        println("1. blockingGet `$it` thread: ${Thread.currentThread()}")
                        return@map it
                    }
                    .blockingGet()
            println("2. blockingGet `$result` thread: ${Thread.currentThread()}")
        }
    }
    

    is

     1. blockingGet `Hello` thread: Thread[RxCachedThreadScheduler-1,5,main]
     2. blockingGet `Hello` thread: Thread[main,5,main]
    

    As you can see result was generated on main thread (line 2), the map function was execute in the RxCachedThreadScheduler thread.

    With the line .observeOn(AndroidSchedulers.mainThread()) decommented the blockingGet() never return and all is stucked.

提交回复
热议问题