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?
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
fun getData(): Observable<List<Data>> {
return Observable.fromCallable {
query.search()
}
}
In this case the query.search
will be called in whatever thread is defined in this Rx chain (using subscribeOn
).