Search code examples
observablerx-java2publish-subscribeobserver-patternrx-kotlin2

Observable.never() in "non testing" production code and it is not disposed explicity?


Following is coded:

PublishSubject.create<Pojo>
   .doOnNext{ 
      //..
   }
   .debounce { 
      if (timeout > 0) Observable.timer(timeout, TimeUnit.MILLISECONDS) 
      else Observable.never() 
   }

As it can be seen, there is an Observable.never(), what I understand as nothing shall be triggered when timeout is negative.

Accroding to Observable.never() documentation:

Returns an Observable that never sends any items or notifications to an Observer. This ObservableSource is useful primarily for testing purposes.

Scheduler: never does not operate by default on a particular Scheduler. Type Parameters: T - the type of items (not) emitted by the ObservableSource Returns: an Observable that never emits any items or sends any notifications to an Observer

The "useful primarily for testing purposes" confused me. Is the above example valid with never()? Since it is not disposed explcitly, it that ok?


Solution

  • never() never signals thus when you need an Observable somewhere but don't really need an item or completion to be signaled, you can use it there. Sometimes we need to test certain operator states which need an Observable as a parameter but not trigger any value at all (for example, creating endless windows).

    In your use case, it is probably wrong because debounce suppresses items coming after the current item for the duration of that inner Observable. The end of that duration is a signal from the Observable but never doesn't ever signal, thus all subsequent items will be dropped and debounce won't signal anything, not even completion.

    The question is, what did you intend to do with the next item following the current current item for timeout <= 0? If you don't want to suppress the next item, just return Observable.empty() instead.