O.MeeKoh
O.MeeKoh

Reputation: 2156

Does RxJs .first() operator (among others) complete the source observable?

If I have the following code:

const subject = new BehaviorSubject<[]>([]);
const observable = subject.asObservable();
subject.next([{color: 'blue'}])
observable.pipe(first()).subscribe(v => console.log(v))

According to the docs:

If called with no arguments, first emits the first value of the source Observable, then completes....

Does this mean that the source observable(the BehaviorSubject in this case) completes and you can no longer use it? As in you can no longer call .next([...]) on it.

I'm trying to understand how can an observable complete if it doesnt have the .complete() method on it?

I was trying to look at the source code of first() which under the covers uses take() and in turn take() uses lift() so I was curious if somehow first operator returns a copy of the source observable(the subject) and completes that.

Upvotes: 0

Views: 857

Answers (1)

MigueMike
MigueMike

Reputation: 199

The source observable is not completing, what it completes is the subscription. You could have multiple subscriptions on your Observable source, in your case one BehaviorSubject.

subject.next([{color: 'blue'}])
subject.next([{color: 'red'}])
const subs1 = observable.pipe(first()).subscribe(v => console.log(v))
const subs2 = observable.subscribe(v => console.log(v))

In the example above you clearly see that the source is not completing, just the subscription.

I have created a Stackblitz if you want to try it: https://stackblitz.com/edit/rxjs-uv6h6i

Hope I got your point!

Cheers :)

Upvotes: 1

Related Questions