【问题标题】:Create observable from object that stays alive从存活的对象创建可观察对象
【发布时间】:2018-03-04 14:28:30
【问题描述】:

我是 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 的每次更改仅发出一次更改?

【问题讨论】:

    标签: angular rxjs observable store subscription


    【解决方案1】:

    您需要使用SubjectBehaviorSubject

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

    【讨论】:

    • 谢谢,能给你一个基本的例子来说明它是如何使用的吗?我正在阅读文档,但示例会有所帮助。当我尝试将其应用于我的对象时,他们的示例没有意义
    • Here 是我回答的另一个非常相似的问题。它提供了一个很好的基本BehvaiorSubject 用法示例。
    • 谢谢@joshrathke - 你用示例代码回答了另一个问题,为我提供了让它工作所需的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    相关资源
    最近更新 更多