1
votes

RxJS version: 5.5.6

Code to reproduce:

var obs = Rx.Observable.interval(100)
                  .startWith(0)
                  .flatMap(() => {
                       return Rx.Observable.empty();
                  });

var sub = obs.subscribe(
          (data) => {console.log(data, 1)},
          (err) => {console.log(err, 2)},
          () => {console.log(3)}
);

The above code logs nothing

Expected behavior: next, complete callback should be triggered

Actual behavior: subscribe callbacks not been invoked

Additional information:

if we flatMap returns Rx.Observable.of({}), then callbacks get invoked.

according to RxJS documentation Observable.never() Creates an Observable that emits no items to the Observer.

Observable.empty() Creates an Observable that emits no items to the Observer and immediately emits a complete notification.

var obs = Rx.Observable.empty();

var sub = obs.subscribe(
(data) => {
    console.log(data, 1);
},
(err) => {
    console.log(err, 2);
},
() => {
    console.log(3);
},
);

//the above code logs 3

If we use Observable.interval() then Observable.empty does not emit a complete notification

1

1 Answers

1
votes

While Observable.empty() is an observable that complete right away without emits any thing, it is returned from flatMap, thus it's complete signal is omitted. The observable above is an observable that "never" end (only when the subscription is unsubscribed) and never emits anything.

When you use the flatMap operator, your observable use the returned observable of the map function, take the emitted items (not the complete signal, error will still buble up though) and emits them. Because your map function returns an Observable.empty(), the flatMap operator found no items to emit, skip the complete signal and returns nothing.

Difference between empty and never is, as in the doc, while both will not emits any item, one will signal that it's completed (empty) and one will not (never).