Chickin Nick
Chickin Nick

Reputation: 547

SwitchMap with delayed observable

 Observable
     .interval(2, TimeUnit.SECONDS)
     .switchMap(integer -> 
        Observable
                 .just(integer * 2) 
                 .delay(5,SECONDS))
     .subscribe(integer -> { System.out.println(integer);});

As I understood, after switch map we should subscribe to last created observable, so I expect output "8" after 20 seconds, but it waits forever

Upvotes: 1

Views: 2243

Answers (1)

Bob Dalgleish
Bob Dalgleish

Reputation: 8227

The operation of switchMap() operator goes as follows:

  1. Receive a value emitted from upstream
  2. Invoke the function argument with the emitted value, which must be an observable
  3. Subscribe to the observable
  4. Emit any items from that observable
  5. When a new item is emitted from upstream, unsubscribe from the observable in step 3, and start at step 2.

The result is that the delayed observable will never emit anything because it will be unsubscribed every 2 seconds.

You will need to use flatMap() operator instead, which will not unsubscribe on each emitted value.

Upvotes: 1

Related Questions