只有创建视图层次结构的原始线程才能触及其视图。 RxAndroid

时间:2017-11-09 14:23:52

标签: android retrofit2 rx-android

我尝试使用RxAndroid

button.setOnClickListener(view -> restApiFactory.testService().getListTest(7)
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<List<Test>>() {

我收到错误

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

我没有AndroidSchedulers.mainThread()

1 个答案:

答案 0 :(得分:12)

你需要从主线程中操纵UI所以为了做到这一点你需要告诉rxandroid通知主线程的变化所以使用

button.setOnClickListener(view -> restApiFactory.testService().getListTest(7)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                //              ^^^^^^^^^^
                .subscribe(new Observer<List<Test>>() {

要获得此功能,需要依赖

compile 'io.reactivex.rxjava2:rxandroid:2.0.1' 

并且您当前的依赖项用于进行改造返回rxAndroid类型响应。