BlockingGet块UI线程RxJava 2 [英] BlockingGet block UI thread RxJava 2
问题描述
我正在处理这个问题.
I am dealing with the problem.
我试图以同步方式调用RxJava,但是这样做会导致主线程阻塞.
I am trying to call RxJava in the sync manner, however doing that results in blocking the Main thread.
这是我的代码
@Override
public Single<SettingsBundle> getSettings() {
SettingsBundle settingsModel = mSettingsManager.getSettings();
return Single.just(settingsModel).map(mSettingsMapper);
}
这是我的同步通话
@Override
public SettingsBundle getSettingsSync() {
return getSettings().blockingGet();
}
在调用getSettingsSync
时,主线程被阻止,但是有时它可以正常工作,这更成问题了.
When calling the getSettingsSync
the Main thread is blocked, however sometimes it works fine, what is more problematic.
我已经尝试过类似的东西
I have tried something like that
@Override
public SettingsBundle getSettingsSync() {
return getSettings()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.blockingGet();
}
但是它仍然被阻止.
我做错了,我将不胜感激.
What I am doing wrong, I would be grateful for any help.
谢谢.
推荐答案
TL; TR
切勿将observeOn(AndroidSchedulers.mainThread())
与blockingGet()
一起使用
长版
输出为:
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()}")
}
}
是
1. blockingGet `Hello` thread: Thread[RxCachedThreadScheduler-1,5,main]
2. blockingGet `Hello` thread: Thread[main,5,main]
您可以看到结果是在主线程(第2行)上生成的,映射函数是在RxCachedThreadScheduler线程中执行的.
As you can see result was generated on main thread (line 2), the map function was execute in the RxCachedThreadScheduler thread.
随着行.observeOn(AndroidSchedulers.mainThread())
的分解,blockingGet()
永不返回,并且全部卡住.
With the line .observeOn(AndroidSchedulers.mainThread())
decommented the blockingGet()
never return and all is stucked.
这篇关于BlockingGet块UI线程RxJava 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!