并行执行是将.subscribeOn(Schedulers.~~~)写在flatmap里面。
val executor = Executors.newFixedThreadPool(10)
Observable.range(0, 20)
.flatMap { i ->
Observable.create<Int>({ e -> e.onNext(sleep(i)) })
.subscribeOn(Schedulers.from(executor))
}
这样给每一个任务分别指定执行线程,注意这里如果不使用线程池Schedulers.from(executor),而是Schedulers.newThread(),io()等,会给每一个任务都开线程,任务太多的话,资源不够,程序可能崩溃
如果写在flatmap外面:
fun main(args: Array<String>) {
val executor = Executors.newFixedThreadPool(10)
Observable.range(0, 20)
.flatMap { i -> Observable.create<Int>({ e -> e.onNext(sleep(i)) }) }
.subscribeOn(Schedulers.from(executor))
.subscribe { i -> println(i) }
}
fun sleep(i : Int): Int{
Thread.sleep(100)
return i
}
``
打印顺序是0,1,2,3,...。用时2秒
并行执行
fun main(args: Array<String>) {
val executor = Executors.newFixedThreadPool(10)
Observable.range(0, 20)
.flatMap { i ->
Observable.create<Int>({ e -> e.onNext(sleep(i)) })
.subscribeOn(Schedulers.from(executor))
}
.subscribe { i -> println(i) }
}
fun sleep(i : Int): Int{
Thread.sleep(100)
return i
}
``
打印是出的字符无序的,用时0.3秒