androidretrofit2rx-android

Only the original thread that created a view hierarchy can touch its views. RxAndroid


I tried using RxAndroid

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

but I got the following error :

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

I have not Used AndroidSchedulers.mainThread()


Solution

  • You need to manipulate UI from main thread so in order to do that you need to tell rxandroid to notify changes on main thread so use

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

    and to obtain this, you need to have a dependency as

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

    and your current dependencies are used to make retrofit retuns rxAndroid type response.