RxJS - BehaviorSubject does not trigger onComplete callback

I've been developing an Angular 7 application and using BehaviorSubject to manage the user authentication state, following the widely recommended practice from various sources online.

However, I've come across a puzzling issue - given that BehaviorSubject is an Observable, why am I unable to trigger the onComplete() method?

Here's the code snippet I'm working with, which appears quite standard:

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

The authService instance setup looks like this:

authenticationState = new BehaviorSubject(false);

Despite my efforts, 'complete' doesn't get printed in the console. Could there be a mistake in my approach?

SOLUTION

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

After making this adjustment, the complete() method successfully gets executed.

Answer №1

In the realm of Observables, the complete function is triggered only when all the items in the stream have been emitted. In other words, it signals the end of a non-erroneous Observable.

If you find yourself needing just one item from the Observable, you can achieve this by:

authenticationState.first().subscribe();

By doing so, the complete event will be executed after that single emitted item has been received.

Answer №2

When you're prepared for the completion section of the subscription to be triggered, it can be done like this.

authenticationState.complete();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating aws-sdk into Angular 2 for enhanced functionality

I'm currently working on integrating my Angular2 application with an s3 bucket on my AWS account for reading and writing data. In the past, we used the aws-sdk in AngularJS (and most other projects), so I assumed that the same would apply to Angular2 ...

Dealing with Errors in Angular's HttpClient

I've been facing some challenges when it comes to running code after an error occurs in HttpClient. I need help with setting a flag that will stop a loading spinner when the HTTP call fails. My project uses RxJs 5.5.2 and Angular 5. private fetch() ...

The header of the data table does not adapt well to different screen

I am currently experiencing an issue with my Angular data table. Everything works fine until I add the option parameter "scrollY: '200px'" or "scrollY: '50vh'", which causes a bug in my table header. It becomes unresponsive, and the siz ...

Converting a file into a string using Angular and TypeScript (byte by byte)

I am looking to upload a file and send it as type $byte to the endpoint using the POST method My approach involves converting the file to base64, and then from there to byte. I couldn't find a direct way to convert it to byte, so my reasoning may be ...

Using TypeScript to create a fullscreen video mode in HTML

Could someone provide guidance on enabling fullscreen mode when using the video tag? I am currently utilizing the following typescript: let vid = <HTMLVideoElement> document.getElementById('video1'); I want to play the video in fullscreen ...

What is the best way to manage multiple data operations simultaneously using ngrx?

In collaboration with the entirety of the "flux architecture" (actions, effects, reducers, etc.) along with rxjs, my aim is to create and delete multiple data. However, I am facing the following challenges: How can I create or delete multiple data in bo ...

Detecting when Angular2 input values change

Here is the updated code snippet: I am attempting to modify an input field and then submit the form. However, when I retrieve the form data using server-side code, the input has not been updated. <form id="cardsForm" method="post"> <inpu ...

Error: monaco has not been declared

My goal is to integrate the Microsoft Monaco editor with Angular 2. The approach I am taking involves checking for the presence of monaco before initializing it and creating an editor using monaco.editor.create(). However, despite loading the editor.main.j ...

Tips for Crafting a Mutation Response Evaluation

When I execute a graphql mutation, the code looks like this: interface SignInReponse { loginEmail : { accessToken: string; } } const [login] = useMutation<SignInReponse>(LOGIN); This is how the mutation appears in the schema: loginEmail( ...

Tips on harnessing the power of CreateReducer within the ActionReducerMap<State> entity?

I'm trying to use the CreateReducer method to create a reducer, but I'm running into issues and not sure why it's not working. I attempted to modify the State class, but that doesn't seem to be the right approach. export const reducer ...

gyp ALERT: Received a warning of EACCES when attempting to install angular/cli

Working on Ubuntu 17.04 with Node 8.9.4 LTS installed, I encountered an error loop while trying to install Angular CLI using npm. gyp WARN EACCES user "root" does not have permission to access the dev dir "/usr/lib/node_modules/@angular/cli/node_modules/n ...

Issue with the `instanceof` operator not functioning properly when used with Immutable.js

We've encountered an issue while upgrading our project from typescript2.4 to typescript3.2 specifically with immutable.js. Prior to the update, simply using if(x instanceof Immutable.Iterable) would result in the type of x being Immutable.Iterable< ...

When trying to import a module in Angular, an error is encountered while using Scully

Exploring the utilization of Scully within my Angular project has presented me with a challenge. In Angular, Modules must be imported in order to use them effectively. However, when attempting to execute Scully through the command line: npm run scully --sc ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

Tips for validating the loading variable during testing of the mockservice in angular5

In the process of creating a test case suite for my application, I am faced with the challenge of verifying and validating the loading variable in my component spec file. The scenario involves calling an API service from my component to retrieve data, show ...

I am experiencing issues with arrow pagination not functioning properly in TypeScript

My current project involves building a customer table with 10 customers displayed on each page. Additionally, there are arrows below the table to help users navigate and view more customers. Unfortunately, there seems to be an issue with the functionality ...

Follow the correct sequence when tapping the pipes and disregard the outcomes

I'm having trouble with executing tap functions in observables. In my scenario, I have a series of API requests that are dependent on each other. To handle this, I store the necessary data for the next request in class properties and use tap function ...

Show real-time validation messages as the form control values are updated

Instructions: Visit Plunker Locate the input box labeled 'Name' Do not enter anything in the 'Name' field Move to the 'Email' field and start typing An error message will appear for the 'Name' field as you type in ...

The Custom Layout Component in Form.io

I am currently working with Form.io v3.27.1 and I'm in the process of developing a custom layout component, specifically an accordion. I have been referring to the concepts outlined in the CheckMatrix component example as my guide. Successfully, I ha ...

Can TypeScript be used to dynamically render elements with props?

After extensive research on SO and the wider web, I'm struggling to find a solution. I have devised two components, Link and Button. In short, these act as wrappers for <a> and <button> elements with additional features like chevrons on t ...