簡體   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