RxJS - Auto Unsubscribe from Observable after first value
Built with RxJS 6+
This is a quick post to show how you can automatically unsubscribe from an RxJS observable after the first value is emitted and the subscription is executed once.
The RxJS first()
operator
The RxJS first()
operator waits until the first value is emitted from an observable and then automatically unsubscribes, so there is no need to explicitly unsubscribe from the subscription.
observable.pipe(first()).subscribe(x => { ... });
Example Angular component with RxJS first()
operator
This is the home component from an Angular 10 tutorial that automatically unsubscribes from the userService.getAll()
observable after the users are loaded by piping it through the RxJS first()
operator.
The full tutorial is available at Angular 10 - JWT Authentication with Refresh Tokens.
import { Component } from '@angular/core';
import { first } from 'rxjs/operators';
import { User } from '@app/_models';
import { UserService } from '@app/_services';
@Component({ templateUrl: 'home.component.html' })
export class HomeComponent {
loading = false;
users: User[];
constructor(private userService: UserService) { }
ngOnInit() {
this.loading = true;
this.userService.getAll().pipe(first()).subscribe(users => {
this.loading = false;
this.users = users;
});
}
}
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Follow me on Twitter at https://twitter.com/jason_watmore
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some RxJS Help?
Search fiverr to find help quickly from experienced RxJS developers.