Home:ALL Converter>Reactivex Observable blocking UI thread

Reactivex Observable blocking UI thread

Ask Time:2019-02-23T04:58:49         Author:Mr. Thanks a lot

Json Formatter

So Im using a MVVM pattern with Rx, the thing is when I run the operation that is suppose to run in a background thread my UI thread gets blocked, this is my viewmodel:

class dataViewModel (application: Application): AndroidViewModel(application) {
        val dataRepository = DataRepository.getInstance(application.applicationContext)
        val listData = MutableLiveData<List<Data>>()
        var isLoading = MutableLiveData<Boolean>()

        fun loadData(){
            isLoading.value = true
            dataRepository.getData().subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeWith(object: DisposableObserver<List<Data>>(){
                        override fun onComplete() {
                            //Update UI
                            isLoading.value = false
                        }
                        override fun onNext(retrievedData: List<data>) {
                            listData.value = retrievedData
                        }
                        override fun onError(e: Throwable) {
                            //Handle error
                        }
                    })
        }
    }

And this is the repository method:

fun getData(): Observable<List<Data>> {
    var dataList = query.search //this query may take a while and blocks the UI thread
    return Observable.just(dataList)
}

I'm I missing something?

Author:Mr. Thanks a lot,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/54835087/reactivex-observable-blocking-ui-thread
Demigod :

Your query.search happens in the UI thread, becuase you're calling it before your Rx operators will be involved. You should change getData method to\n\nfun getData(): Observable<List<Data>> {\n return Observable.fromCallable {\n query.search()\n }\n}\n\n\nIn this case the query.search will be called in whatever thread is defined in this Rx chain (using subscribeOn).",
2019-02-22T21:16:08
yy