Azoulay Jason
Azoulay Jason

Reputation: 2999

RxJS - BehaviorSubject, onComplete not called

I'm building an Angular 7 app and using BehaviorSubject to keep the user authentication state as it's recommended on every source on the internet.

Since BehaviorSubject is an Observable, why can't I fire the onComplete() method?

Here's the code (which seems pretty classic to me):

this.authService.authenticationState.subscribe(state => {
      this.isLoggedIn = state;
    },
    err => console.log(err),
    () => console.log('complete')
    );

authService

authenticationState = new BehaviorSubject(false);

'complete' is not logged. Is there something I'm doing wrong?

SOLUTION

this.authService.authenticationState.subscribe(state => {
      this.isLoggedIn = state;
      this.authService.authenticationState.complete();
    },
    err => console.log(err),
    () => console.log('complete')
    );

then the complete() method is fired

Upvotes: 2

Views: 1589

Answers (2)

Nitsan Avni
Nitsan Avni

Reputation: 841

complete is only called when an Observable is done emitting items. IOW it's the last event from a non-erroneous Observable.

If you're only interested in a single item from this Observable you could:

authenticationState.first().subscribe();

This way the complete will be called after the single emitted item.

Upvotes: 3

dev-dan
dev-dan

Reputation: 6293

I think you can trigger complete like this when you are ready for the complete section of the subscription to be called.

authenticationState.complete();

Upvotes: 1

Related Questions