RxJava线程切换

时间:2017-08-07 20:48:12

标签: java android multithreading rx-java rx-binding

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));

上面的代码抛出了这个异常:

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事件,然后将项目映射到其标题(在主线程上),然后在后台线程上运行一个长操作,然后在主线程上接收该操作的输出再次。请帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:2)

你遇到了在仓库中修复但尚未发布的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));