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;
});
}
}
Need Some RxJS Help?
Search fiverr for freelance RxJS developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!