[英]Rx Java: Sleep before OnNext (Sleep before emitting from Observable)
基於我的 Observable 中的一個條件,我想延遲 onNext / onError。 我的代碼如下:
fun check3(){
val list = arrayListOf(1,2,3,4,5,6,7, null)
val obs = Observable.create<Int> { subscriber ->
list.filter {
it != null
}.map {
if (it!! %2 == 0 ) {
Thread.sleep(3000)
subscriber.onError(IllegalArgumentException("Mod is true"))
} else {
subscriber.onNext(it)
subscriber.onComplete()
}
}
}
}
這里的痛點是 Thread.sleep(3000)
有沒有更好的方法來做到這一點? 基本上,如果滿足 if(it %2) 條件,我想延遲向訂閱者發送 onError 通知
您可以使用concatMap
將睡眠轉換為非阻塞延遲:
Observable.fromIterable(list.filter { it != null })
.concatMap {
if (it!! % 2 == 0) {
return@concatMap Observable.error(IllegalArgumentException("Mod is true"))
.delay(3, TimeUnit.SECONDS, true)
}
Observable.just(it)
}
.take(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.