Search code examples
androidrx-javarx-java2

RxJava combine publishsubject with timeout


I want to be able to subscribe to publishsubject and wait for result, but no longer than 1 minute.

The problem is that if I do

publishsubject.timeout(1, TimeUnit.MINUTES).subscribe({result -> ... }, {error -> ... } )

I always get error even if before that I successfully get result. How to properly implement this approach?


Solution

  • You most likely get the timeout exception because timeout requires your source keeps producing items or completes within the specified time window. Thus, if you just signal one onNext to the PublishSubjectand never more, you'll get a timeout due to lack of a second onNext call.

    So if you want one item, use take (before or after timeout):

    publishsubject
       .timeout(1, TimeUnit.MINUTES)
       .take(1)
       .subscribe(result -> { /* ... */ }, error -> { /* ... */ } )