8

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

10
  • UI should be updated from main thread , there is no escape from that Commented Nov 9, 2017 at 14:28
  • I know. but I do not know how to tell the observer main thread
    – ip696
    Commented Nov 9, 2017 at 14:29
  • add this ..observeOn(AndroidSchedulers.mainThread()) before .subscribe(new Observer<List<Te... Commented Nov 9, 2017 at 14:33
  • I wrot in my question - I have not AndroidSchedulers class
    – ip696
    Commented Nov 9, 2017 at 14:34
  • and i also said , there is no escape and what do you mean by you don't have AndroidSchedulers class? you need to be specific regarding the issue and constraints Commented Nov 9, 2017 at 14:36

2 Answers 2

22

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.

3
  • Can't we do without adding compile 'io.reactivex.rxjava2:rxandroid:2.0.1' this dependency. Can't we use Schedulers? I tried to use Schedulers.trampoline() & Schedulers.newThread() but giving me same error. Any idea?@Pavneet_Singh Commented Jun 18, 2018 at 14:11
  • @MaulikDodia I think it should work, hopefully you are not using any UI related work Commented Jun 19, 2018 at 23:47
  • It wasn't working, that's what I'm saying@Pavneet_Singh Commented Jun 20, 2018 at 4:51
1

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

Use as:-

.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.