Reputation: 13103
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?
Upvotes: 0
Views: 582
Reputation: 1374
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.
Upvotes: 1