I'm Trying to load some data from a web server in my application. And Because of the async nature of the operation, there is no way to know ahead of time how long it will take to complete. To alert the user that the operation is “in progress.”, I'am using a loading indicator.
This is the a came up with using kotlin and RxJava 2 ( I hope it's clear):
fun loadData(){
showLoader() // show loading indicator
Single.fromCallable {
// http request logic goes here
}.delay(1000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableSingleObserver<String>() {
override fun onSuccess(data: String) {
// do something
hideLoader() // on success, hide indicator
}
override fun onError(e: Throwable) {
displayErrorMessage()
hideLoader() // on error hide indicator
}
})
}
I want to show the loading indicator for at least 1 second so I used the delay()
operator, but the problem is this works as expected if the operation succeeded, but in case of an error, the indicator will disappear immediately not after 1 second.
So is there a way I can make the onError()
method execute after 1 second? Thanks
Observable.timer(1, TimeUnit.SECONDS).switchMapSingle { Single.fromCallable { //... } }
? – Sequestrationtimer()
operator directly on the Single instead of converting it to an Observable first? – Herzegovina