I am facing an issue with two services in my application. Each service has an observable, and I have a component that is supposed to get the last emitted value of both observables. However, I noticed that the combineLatest
function fires as soon as one observable changes, instead of waiting for 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);
}
}
Upon calling the function, I receive values in the combineLatest()
at 2500ms and 5000ms.