Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 862
ip696 Avatar asked Nov 09 '17 14:11

ip696


2 Answers

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.

like image 64
Pavneet_Singh Avatar answered Nov 11 '22 14:11

Pavneet_Singh


You should be using observeOn(AndroidSchedulers.mainThread()) not subscribeOn(AndroidSchedulers.mainThread()).

Use as:-

.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
like image 1
RASHMI RANJAN Avatar answered Nov 11 '22 15:11

RASHMI RANJAN