I have 2 services which both have a observable, and a component that should get the last emitted value of both observables but the combineLast
already fires when 1 observable changes, not both:
export class CreateSessionComponent {
constructor(
private sessionService: SessionService,
private userService: UserService
) {
combineLatest([this.userService.user$, this.sessionService.session$])
.subscribe({
next: (data) => console.log(data),
});
}
public createUserAndSession(): void {
this.sessionService.createSession();
this.userService.createUser();
}
}
export class UserService {
private userSubject = new BehaviorSubject<any | null>(null);
public user$ = this.userSubject.asObservable();
public createUser(): void {
setTimeout(() => {
this.userSubject.next(`User ${Math.random()} `);
}, 5000);
}
}
export class SessionService {
private sessionSubject = new BehaviorSubject<any | null>(null);
public session$ = this.sessionSubject.asObservable();
public createSession(): void {
setTimeout(() => {
this.sessionSubject.next(`Session ${Math.random()} `);
}, 2500);
}
}
When the function is called I get a value in the combineLatest()
at both 2500ms and 5000ms.
combineLatest
works on the principle: When any observable emits a value, emit the last emitted value from each.
If you want to wait for both of your observables to emit the values, you should use zip
instead of combineLatest
, I've modified your below create-session.component.ts
:
import { Component } from '@angular/core';
import { zip } from 'rxjs';
import { SessionService } from '../session.service';
import { UserService } from '../user/user.service';
@Component({
selector: 'app-create-session',
templateUrl: './create-session.component.html',
styleUrls: ['./create-session.component.css'],
})
export class CreateSessionComponent {
constructor(
private sessionService: SessionService,
private userService: UserService
) {
zip(this.userService.user$, this.sessionService.session$)
.subscribe({
next: (data) => console.log(data),
});
}
public createUserAndSession(): void {
this.sessionService.createSession();
this.userService.createUser();
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments