并行執(zhí)行是將.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))
}
這樣給每一個(gè)任務(wù)分別指定執(zhí)行線程,注意這里如果不使用線程池Schedulers.from(executor)穗慕,而是Schedulers.newThread()饿敲,io()等,會(huì)給每一個(gè)任務(wù)都開(kāi)線程逛绵,任務(wù)太多的話怀各,資源不夠倔韭,程序可能崩潰
如果寫在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,...。用時(shí)2秒
并行執(zhí)行
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
}
``
打印是出的字符無(wú)序的瓢对,用時(shí)0.3秒