typescript combineLatest不等待observable发出值

r6vfmomb  于 2023-03-04  发布在  TypeScript
关注(0)|答案(2)|浏览(158)

我有2个服务,它们都有一个可观察值,还有一个组件 * 应该 * 获得这两个可观察值的最后一个发出值,但combineLast已经在1个可观察值发生变化时触发,而不是同时触发:

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);
  }
}

当调用该函数时,我在2500ms和5000ms时都在combineLatest()中获得一个值。
https://stackblitz.com/edit/angular7-rxjs-g435xp

laik7k3q

laik7k3q1#

combineLatest的工作原理是:When any observable emits a value, emit the last emitted value from each.
如果你想等待你的两个可观测量都发出值,你应该使用zip而不是combineLatest,我已经修改了下面的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();
  }
}
9fkzdhlc

9fkzdhlc2#

您希望过滤掉空值,以便它仅在两个可观察对象都有值时才发射

combineLatest([this.userService.user$, this.sessionService.session$]).pipe(
  filter(([user, session]) => user !== null && session !== null)
)

如果其中一个为空,这将停止发射,然后在createUsercreateSession中,确保在发射可观察对象之前将它们设置为空。

相关问题