从保持活动状态的对象创建可观察对象

Create observable from object that stays alive

我是 RxJS 的新手。我想创建一个可能随时更改的 AppState 对象的可观察对象,并订阅它以获取这些更改。这是一个精简的实现:

export class AppState {

  public get observable(): Observable<any> {
     return Observable.of(this._state);
  }
}


// appState is injected into my component via angular DI

this.appState.observable
     .subscribe((appState) => {
        console.log('appState: ', appState);)
     }, (err) => {
        console.log('Error: ' + err);
     }, () =>{
        console.log('Completed');
     });

但它只运行一次并立即调用completed。所以当我更改我的 appState 时,订阅已经结束。

如何使订阅永远保持活动状态,例如 KnockOutJS 样式。这用于 Angular 应用程序

更新:我得到它部分与 Subject 一起工作。但现在的问题是它发出了许多相同值的重复项。

// full appState.ts
import { Injectable } from '@angular/core';
import { Observable, Subject, BehaviorSubject } from 'rxjs';

export type InternalStateType = {
   [key: string]: any
};

@Injectable()
export class AppState {

   public _state: InternalStateType = {};
   public subject: Subject<any>;

   constructor() {
      this.subject = new Subject();
   }

   /**
    * Return an observable for subscribing to.
    */
   public get observable() {
      return this.subject;
   }

   /**
    * Return a clone of the current state.
    */
   public get state() {
      this._state = this._clone(this._state);
      this.subject.next(this._state);
      return this._state;
   }

   /**
    * Never allow mutation
    */
   public set state(value) {
      throw new Error('do not mutate the `.state` directly');
   }

   public get(prop?: any) {
      /**
       * Use our state getter for the clone.
       */
      const state = this.state;
      return state.hasOwnProperty(prop) ? state[prop] : state;
   }

   public set(prop: string, value: any) {
      /**
       * Internally mutate our state.
       */
      return this._state[prop] = value;
   }

   private _clone(object: InternalStateType) {
      /**
       * Simple object clone.
       */
      return JSON.parse(JSON.stringify(object));
   }
}

需要更改什么才能让它对 this._state 的每次更改仅发出一次更改?

您需要使用 Subject, or a BehaviorSubject

Subject 将在订阅者传递给 Subject 时向订阅者发出值,而 BehaviorSubject 将发出订阅时给出的最后一个值,然后在值可用时继续发出值。