Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
Filter all 'null' values from an Observable<T>

I have a service with a subject:

@Injectable() export class UserService() {
    private currentUserSubject = new BehaviorSubject<User>(null);
    public currentUser = this.currentUserSubject.asObservable().distinctUntilChanged(); 

    ... // emitting new User    
}

Have a component I inject this service into and subscribing on updates:

@Component() export class UserComponent {
    constructor(private userService: UserService) {
        this.userService.currentUser
            .subscribe((user) => {
                // I want to see not null value here
            })
    }
}

I want to apply something to Observable<User> to filter all null values and get into subscribe only when User is actually loaded.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Add a filter operator to your observable chain. You can filter nulls explicitly or just check that your user is truthy - you will have to make that call depending on your needs.

Filtering out null users only:

public currentUser = this.currentUserSubject
                         .asObservable()
                         .filter(user => user !== null)
                         .distinctUntilChanged(); 
over 4 years ago · Santiago Trujillo Report

0

Another way to check the value exists:

public currentUser = this.currentUserSubject
                         .asObservable()
                         .filter<User>(Boolean)
                         .distinctUntilChanged(); 
over 4 years ago · Santiago Trujillo Report

0

with rxjs@6 and typescript the recommended (readable/maintainable) way is to define the following type guard:

export function isNonNull<T>(value: T): value is NonNullable<T> {
  return value != null;
}

and augment a subject with pipe and filter:

subject.pipe(filter(isNonNull))
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!