Search code examples
kotlinrx-javarx-java2

subscribeOn(Schedulers.io()) not working but subscribeOn(Schedulers.trampoline()) does


fun main() {
    Single.just("faefw")
        .subscribeOn(Schedulers.trampoline())
        .map {
            println("map in thread ${Thread.currentThread().name}")
        }
        .flatMap {
            return@flatMap Single.just(231).map {
                println("map in thread ${Thread.currentThread().name}")
                return@map it
            }
        }
        .subscribe({
            println(it)
        }, {
            println(it)
        })
}

prints out:

map in thread main
map in thread main
231

But

fun main() {
    Single.just("faefw")
        .subscribeOn(Schedulers.io())
        .map {
            println("map in thread ${Thread.currentThread().name}")
        }
        .flatMap {
            return@flatMap Single.just(231).map {
                println("map in thread ${Thread.currentThread().name}")
                return@map it
            }
        }
        .subscribe({
            println(it)
        }, {
            println(it)
        })
}

outputs nothing!

subscribeOn(Schedulers.computation()) and subscribeOn(Schedulers.newThread()) do not work either

Why?


Solution

  • The program is exiting before the code has time to execute. Try with a sleep or put in a print statement after subscribe

    fun main() {
        Single.just("faefw")
            .subscribeOn(Schedulers.io())
            .map {
                println("map in thread ${Thread.currentThread().name}")
            }
            .flatMap {
                return@flatMap Single.just(231).map {
                    println("map in thread ${Thread.currentThread().name}")
                    return@map it
                }
            }
            .subscribe({
                println(it)
            }, {
                println(it)
            })
        println("just subscribed in last statement!")
        Thread.sleep(500)
        println("exiting main thread...")
    }
    

    with trampoline the output is

    map in thread main
    map in thread main
    231
    just subscribed in last statement!
    exiting main thread...
    

    with other schedulers which do the "work" in different threads (like .io() and .computation()) will have output like this:

    just subscribed in last statement!
    map in thread RxComputationThreadPool-1
    map in thread RxComputationThreadPool-1
    231
    exiting main thread...
    

    PS. The io() scheduler you can think of as unbounded thread pool, computation() as a bounded thread pool.