RxJava线程切换
问题描述:
RxBottomNavigationView.itemSelections(sections).map(menuItem -> menuItem.getTitle().toString())
.observeOn(AndroidSchedulers.mainThread()).map(this::insertCategoryHeadersForSection)
.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread())
.compose(bindToLifecycle()).subscribe(itemInfos -> dishRecyclerAdapter.animateTo(itemInfos));
上面的代码抛出此异常:RxJava线程切换
java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.
at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:111)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'boolean io.reactivex.internal.fuseable.SimpleQueue.isEmpty()' on a null object reference
at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:172)
at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:252)
at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
我试图从BottomNavigationView得到itemSelections事件,那么该项目映射到它的标题(主线程),然后在后台线程上运行长操作,然后再次在主线程上接收该操作的输出。请帮助。提前致谢。
答
您已遇到bug in RxBinding2固定在回购协议中但尚未发布。其原因是通过使用subscribeOn(Schedulers.computation())
,您不会将计算移动到后台,但会使RxBottomNavigationView.itemSelections(sections)
发生在被禁止的后台线程上并导致您的流(和应用程序)崩溃。
你应该这样做,而不是:
RxBottomNavigationView.itemSelections(sections)
.subscribeOn(AndroidSchedulers.mainThread()) // <------------------------
.map(menuItem -> menuItem.getTitle().toString()) // main thread
.observeOn(Schedulers.computation()) // <------------------------
.map(this::insertCategoryHeadersForSection) // background
.observeOn(AndroidSchedulers.mainThread()) // <------------------------
.compose(bindToLifecycle())
.subscribe(itemInfos -> // main
dishRecyclerAdapter.animateTo(itemInfos));
看起来你有违反通过不调用'onSubscribe'的'Observable'协议的源。我的怀疑是'RxBottomNavigationView.itemSelections(节)''但可以肯定,请使用[协议验证器调试支持](https://github.com/akarnokd/RxJava2Extensions#protocol-validation)。 – akarnokd