subscriptionOnSchedulers.io不起作用,但是subscribeOnSchedulers.trampoline可以

问题描述

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)
        })
}

打印出:

map in thread main
map in thread main
231

但是

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)
        })
}

什么都不输出

subscribeOn(Schedulers.computation())subscribeOn(Schedulers.newThread())都不起作用

为什么?

解决方法

在代码有时间执行之前,程序正在退出。订阅后请尝试睡眠或输入打印语句

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...")
}

蹦床的输出是

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

与在不同线程中执行“工作”的其他调度程序(例如.io().computation())将具有以下输出:

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

PS。您可以将io()调度程序视为无界线程池,将computation()视为有界线程池。