How run doOnSubscribe on MainThread in this case

295 Views Asked by At

I want to execute doOnSubscribe block on the main thread. I'm trying this:

fun test(){
    Single
        .fromCallable {
            print(Thread.currentThread())
            getCachedProfile()
        }
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap {
            print(Thread.currentThread())
            api
                .getProfile()
                .doOnSubscribe {
                    print(Thread.currentThread())
                }
                .observeOn(Schedulers.io())
                .map {
                    print(Thread.currentThread())
                    it.profile
                }
                .map { it.id }
                .flatMap { photoId ->
                    print(Thread.currentThread())
                    api
                        .getPhotos(photoId)
                        .map { it.toDomain() }
                }
        }.subscribeOn(Schedulers.io())
        .observeOn(AndroidSchdulers.mainThread())

}

doOnSubscribe run on the main thread, but .getProfile() run on UI thread too and I get an error NetworkOnMainThreadException. How set the schedulers so doOnSubscribe is executed on the main thread and getProfile() run on the IO thread

1

There are 1 best solutions below

0
DevJZ On

Add .subscribeOn(Schedulers.io) to your .getProfile() call so, .getProfile().subscribeOn(Schedulers.io).observeOn(AndroidSchedulers.mainThread().doOnSubscribe()

This is how it's done in java, I imagine Kotlin has the same.

.doOnSubscribe{} is calling something to do before the task is executed

.subscribeOn() tells what thread to do the work on