subscribe not been working as expected with using Observable.empty
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)}
);
Expected behavior: next, complete callback should be triggered
Actual behavior: subscribe callbacks not been invoked
Additional information:
if flatMap returns Rx.Observable.of({}), then callbacks get invoked.
This is expected behavior.
Your interval operator makes the observable hot, meaning it will never complete.
Your flatMap will spawn a new thread every time interval emits, which you then terminate with empty. (empty signals complete(), not next()).
If you want the observable to complete, you gotta use take(x), try it:
Rx.Observable.interval(100)
.take(10)
.startWith(0)
.flatMap(() => {
return Rx.Observable.empty();
});
Hope that makes sense, otherwise someone more qualified will have to explain.
Thanks for your explanation.
If empty() operator emits complete() and not next() signal, then why the complete() callback not been called? only if we add take() operator to the observable .
I'm using this approach to make a polling method. thats why i need it to be infinite.
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
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).
Ref: Answer from my question in stackoverflow
It's simply because hot observables do not complete.
For your complete() handler to trigger, interval has to stop emitting values.
empty itself is completion, but in here main (higher order observable) is interval which you keeps emitting empty and doesn't complete. since it doesn't complete there's no completion, also no next as interval values are mapped into empty instead.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.