Ilker Baltaci
Ilker Baltaci

Reputation: 11787

RxJava/RxKotlin complains about accessing views

I have the following call to retrieve some data from server and update the UI according to response.

    poiAPIService.getPoiDetails(poiId!!)
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { showProgressBar(true) }
            .doFinally { showProgressBar(false) }
            .subscribeOn(Schedulers.io()).subscribe(
                    { poiDetails ->
                        bindPoiDetails(poiDetails)
                    },
                    {
                        (getActivity() as MainOverviewActivity).fragmentControl.hidePoiDetailsFragment()
                    })

}

It complains about showProgressBar that the Views are only accessable on thread that created them. If I change the call like this, everything seems to be fine again.

showProgressBar(true)
poiAPIService.getPoiDetails(poiId!!)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io()).subscribe(
                { poiDetails ->
                    showProgressBar(false)
                    bindPoiDetails(poiDetails)
                },
                {
                    showProgressBar(false)
                    (getActivity() as MainOverviewActivity).fragmentControl.hidePoiDetailsFragment()
                })

}

Upvotes: 1

Views: 165

Answers (2)

Tulsiram Rathod
Tulsiram Rathod

Reputation: 1946

I have done by using below code, using RxJava 2.x

 poiAPIService.getPoiDetails(poiId!!)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(new Consumer < Disposable >() {
                @Override
                public void accept(Disposable disposable) throws Exception {
                    showProgressBar(true);
                }
            })
            .doFinally(new Action () {
                @Override
                public void run() throws Exception {
                    showProgressBar(false);
                }
            })
            .subscribe(/**your subscription here**/);

Try using above code and let me know.

Upvotes: 3

borichellow
borichellow

Reputation: 1001

did you tried to do something like this...

poiAPIService.getPoiDetails(poiId!!)
        .subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(Schedulers.io())
        .doOnSubscribe { showProgressBar(true) }
        .doFinally { showProgressBar(false) }
        .subscribe(
                { poiDetails ->
                    bindPoiDetails(poiDetails)
                },
                {
                    (getActivity() as MainOverviewActivity).fragmentControl.hidePoiDetailsFragment()
                })

pay attention to observeOn and subscribeOn

Looks like you use observeOn and subscribeOn not correctly... take a look to How RXJava Scheduler/Threading works for different operator?

Upvotes: 1

Related Questions