RxJS主题/可观察问题

时间:2018-05-24 05:16:21

标签: angular rxjs observable

我正在尝试将Angular函数转换为可观察模式,因为它的当前实现具有一些异步性。出于本讨论的目的,请使用这个简单的示例。

aFunction(x: boolean){
    if(x){
        // ... do something asynchronous based on the value of x
    }
}

将其转换为使用Observable可以这种方式完成:

anObservableFunction(x: boolean): Observable<any> {
    const result = new Subject();
    if(x){
        // ... do something asynchronous based on the value of x
        // ... where once the actual value you want to return to 
        // the subscribing functions, you can pass in the 
        // result.next(value);
        // result.complete();
    }
    return result.asObservable();
}

我面临的问题(根据我的理解)是为了不访问内部选择语句的实例。

anObservableFunction(x: boolean): Observable<any> {
    const result = new Subject();
    if(x){
        // ... do something asynchronous based on the value of x
        // ... where once the actual value you want to return to 
        // the subscribing functions, you can pass in the 
        // result.next(value);
        // result.complete();
    } else {
        // here
    }
    return result.asObservable();
}

如果使用常规主题,订阅功能肯定不会获得任何值,因为事件的顺序是:

  • 调用函数
  • 主题已创建
  • 设置值
  • 调用函数订阅,因此仅在此事件发生后获取值

如果使用BehaviorSubject或ReplaySubject,它们的初始/构造值将被保留,导致订阅事件不必要地触发?

1 个答案:

答案 0 :(得分:0)

如果值是同步发出的,那么使用Subject会有问题。 BehaviorSubject具有不必要的初始值的缺点,但是ReplaySubject实际上没有那个并且可以工作,但是如果有人稍后订阅了你可能不想要的东西,它也会重放这个值。

一个简单的技巧是通过勾号延迟同步发射:

setTimeout(() => result$.next(42), 0);

但是,您也可以直接返回一个observable并避免使用主题:

foo(x) {
  if(x) {
    return callRemoteEndpoint();
  }

  return of(42);
}