Observable - initiating conditional emission

How can I make sure that values are emitted conditionally from an observable? Specifically, in my scenario, subscribers of the .asObservable() function should only receive a value after the CurrentUser has been initialized.

export class CurrentUser {

    private currentUser$: Observable<CurrentUser>;
    private currentUserBehaviorSubject: BehaviorSubject<CurrentUser>;

    public name: string = "";

    constructor() {
        this.currentUserBehaviorSubject = new BehaviorSubject(this);
        this.currentUser$ = this.currentUserBehaviorSubject.asObservable();
    }

    public asObservable(): Observable<CurrentUser> {
        // 
        if(user.name.length > 0){
            return this.currentUser$;
        }
        else {
            // ?????
        }
    }

    public initialize(string name){
        this.name = name;
        this.currentUserBehaviorSubject.next(this);
    }
}

export class SampleComponent {
    constructor(
        currentUser: CurrentUser
    ) {
        currentUser.asObservable().subscribe(
            (u: CurrentUser) => {
                // i only want an INITIALIZED user here
            },
            error => {},
            () => { }
        );
    }
}

Answer №1

One possible approach is to modify your asObservable() method so it always returns an Observable and utilizes the skipUntil() operator to suppress emissions until currentUserBehaviorSubject emits (indicating that CurrentUser has been initialized):

public asObservable(): Observable<CurrentUser> {
    return this.currentUser$
        .skipUntil(this.currentUserBehaviorSubject);
}

Answer №2

Here's my perspective:

export class CurrentUser {
    subject: Subject<CurrentUser> = new Subject<CurrentUser>();
    observable: Observable<CurrentUser = this.subject.asObservable();

    constructor() {
        // Handle your tasks here
        this.subject.next(this);
    }
}

In your components, simply subscribe to the observable property.

By following this approach, whenever a new CurrentUser is initialized, all observers will be notified. Does this align with your intentions, or am I missing something?

Answer №3

My typical approach for managing such cases is as follows:

  private dataSubject = new BehaviorSubject<any>(null);
  private initSubject$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

getData(): Observable<any> {
  return this.dataSubject.pipe(
    skipUntil(this.initSubject$.pipe(filter(isInitialized => isInitialized === true)))
  )
}

setData(data) {
  this.initSubject$.next(true);
  this.dataSubject.next(data);

}

By following this pattern, the handling of initialized and uninitialized data solely depends on updating the source observable, which is connected to an initialization observable. This can be optimized further by using a static observable for initialization, but the outcome remains the same:

No need for conditional statements in data emission logic; subscribers waiting for data before initialization will simply queue up until the initial data arrives.

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

Using JSDoc to Include TypeScript Definitions

I've been attempting to utilize the ts-xor package, which provides a TypeScript definition: export declare type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U; This is how I'm imp ...

Modifying the values of various data types within a function

Is there a more refined approach to enhancing updateWidget() in order to address the warning in the else scenario? type Widget = { name: string; quantity: number; properties: Record<string,any> } const widget: Widget = { name: " ...

The young one emerges within the SecurePath component temporarily

Setting up authorization in React has been a priority for me. Ensuring that users cannot access unauthorized pages within the application is crucial. To achieve this, I have created a custom component as shown below. import { ReactNode } from "react&q ...

Angular 6 Subscription Issue: Problems with Variable Assignments

Currently, I am working on a map feature that utilizes the mapbox API and relies on the longitudinal and latitudinal coordinates obtained from a geocoder. There is a particular service in place that calls an endpoint with certain parameters. Upon subscrib ...

I am interested in monitoring for any alterations to the @input Object

I've been attempting to detect any changes on the 'draft' Object within the parent component, however ngOnChange() does not seem to be triggering. I have included my code below, but it doesn't even reach the debugger: @Input() draft: ...

What is the best way to monitor parameter changes in a nested route?

I need assistance with managing routes const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListC ...

Guide to updating the background color of a div when clicked using Angular 6

Here is the markup: <mat-card class="example-card" *ngFor="let filteredScreen of filteredScreens" let i = index > <mat-card-header> <div mat-card-avatar class="example-header-image" > <img mat- ...

Leveraging HTTPOnly Cookie for GET request (Accessing user information from server with user_id cookie)

While I was learning from a tutorial, I encountered an interesting scenario where a user id is stored in an HTTPOnly cookie sent by the backend to the frontend after the user logs in. The challenge, however, is that HTTPOnly cookies cannot be accessed by t ...

The current version of npm for @angular 2 has not been released yet

Looking to transition from Angular 2 Beta 15 to Angular 2 RC1. Currently utilizing Visual Studio 2015. Within my npm package.json in Visual Studio, I've inputted: "dependencies": { "@angular/core": "Unavailable", } However, it displays as unav ...

Is it possible to utilize jwt tokens together with Firebase authentication?

Having previously built Spring Boot applications utilizing jwt tokens, Angular 7, and MySQL, I am now considering transitioning to Firebase solely for authentication purposes. Some tutorials suggest that Firebase can be directly implemented through Angular ...

What is causing this error/bug to show up in Angular?

I encountered an error while working on my Angular project that incorporates both front-end and back-end development with Python Flask. Even though the page updates correctly, a database-related error is being displayed in the console. Below are the snippe ...

Step-by-step guide on defining a context variable within a template

I am looking for a way to make my page dependent on a single model object emitted from an Observable. If it was a list, I would use <div ngFor="let currentListItem of myObservable | async" > However, since I only have one model and not a list, ngFo ...

Expose the app's homepage through the nginx server configuration

I currently have a server running Nginx and hosting an Angular 4 application under the domain www.mysite.com. However, I now have another domain called www.mySecondDomain.com and I want this site to open a specific route within the same angular app. For ex ...

Angular 2 - The creation of cyclic dependencies is not allowed

Utilizing a custom XHRBackend class to globally capture 401 errors, I have encountered a dependency chain issue in my code. The hierarchy is as follows: Http -> customXHRBackend -> AuthService -> Http. How can this problem be resolved? export class Custom ...

Angular allows for the creation of a unique webpage layout featuring 6 divs

I am working on a project where I have an image of a car and I need to overlay 6 divs onto the image which can be selected with a mouse click. When a user clicks on one of the divs, it should change color. I've attempted using z-index, but it doesn&ap ...

Navigating through various Angular 7 projects in Express using JWT authentication and role-based routing

In my Angular 7 project, I have developed multiple applications for different roles such as admin, user, and editor. Each role has its own set of components and views. When a logged-in user accesses the application, they are directed to their respective r ...

Do Typescript interfaces check method parameters for validation?

interface optionsParameter { url: string; } function DEC(options: optionsParameter){ } DEC(2) //typescript check compilation error let obj:any = { name: "Hello" } obj.DEC = function(options: optionsParameter){} obj.DEC(1); // no compilation ...

Is Angular mat-icon undergoing a "transformation"?

Overview: The material icon I am using is the "+" sign to represent adding a new item on a webpage. While it displays correctly in English, the Spanish version of the site shows "ñ" instead. Inquiry: Should I leave the tags empty or remove the translati ...

The interaction between Web API, Angular, and the unique MAC Address

My organization currently operates an Application using ASP MVC. However, the application is experiencing slow performance and confusion due to multiple programmers with conflicting ideas. I have taken on the task of refactoring and migrating it to Angular ...

Display the length of the current items in a shopping cart using Angular and RxJS in my template for an ecommerce website

I am trying to create a counter for the number of items in my shopping cart. This counter will be displayed on my home page using Angular 9. I have a function that returns the current number of items in my shopping cart, and I want to display this value i ...