Search code examples
androidrx-javareactive-programmingrx-kotlin

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

}

Solution

  • 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?