Search code examples
javakotlinrx-java2rx-androidrx-kotlin2

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?


Solution

  • 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") }