简体   繁体   中英

Emit value if specific time has passed after last item

I've got an observable: Observable.create<Boolean> {emitter = it} , to which I push some values. I want it to publish a 'false' value, as soon as some specific time period has passed without any value being pushed to that emitter.

How is that possible with RxJava/Kotlin 2?

You can try to combine 2 functions: timeout and onErrorReturn .

Observable.create<Boolean> { 
    // use emitter here
}
     .timeout(3, TimeUnit.SECONDS)
     .onErrorReturn { if (it is TimeoutException) false else throw it } 
     .subscribe { println("onNext $it") }

Updated snippet after clarification. repeatWhen will resubscribe to Observable.

Observable.create<Boolean> { 
    // use emitter here
}
    .timeout(3, TimeUnit.SECONDS)
    .onErrorReturn { if (it is TimeoutException) false else throw it }
    .repeatWhen { it }
    .subscribe { println("onNext $it") }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM