When observable is observed on AndroidSchedulers.mainThread(), Android JUnit tests block indefinitely… here is a solution to the problem.
When observable is observed on AndroidSchedulers.mainThread(), Android JUnit tests block indefinitely
I’m writing a simple test that’s equivalent to:
Test fun testObservable() {
val returnedObservable = Observable.create(object : Observable.OnSubscribe<String> {
override fun call(t: Subscriber<in String>) {
t.onNext("hello")
t.onCompleted()
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
val result = returnedObservable.toBlocking().first()
assertEquals("hello", result)
}
When .observeOn(AndroidSchedulers.mainThread
()) appears, the test blocks indefinitely on returnedObservable.toBlocking().first().
Is there a way to convert the observable to return the result?
returnedObservable
is returned from a method call where .subscribeOn and .observeOn are already applied, so removing them is not an option.
Solution
I guess this is the error mentioned here: https://github.com/ReactiveX/RxAndroid/issues/50
By the way, why don’t you use RxKotlin?
Your example would look much better :
val returnedObservable = observable<String> { subscriber ->
subscriber.onNext("hello")
subscriber.onCompleted()
}
.subscribeOn(Schedules.io())
.observeOn(AndroidSchedulers.mainThread())