繁体   English   中英

RxJS主题/可观察的问题

[英]RxJS Subject/Observable issue

我正在尝试将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();
}

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

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

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

您正确地说,如果值是同步发出的,则使用“主题”会有问题。 BehaviorSubject有一个不必要的初始值的缺点,但是ReplaySubject实际上没有该值并且可以工作,但是如果有人以后订阅您可能不想要的值,它也会重播该值。

一个简单的技巧是将同步发射延迟一个刻度:

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

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

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

  return of(42);
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM