2017-07-14 9 views
1

このプロパティに応じて別のサービスを実行するために、あるサービスで非同期的にプロパティを設定するのを待つ必要があります。Rxjs、プロパティを設定するために待機して通知するのが最善の方法ですか?

これは現在私がこれを解決するためにやっていることですが、Rxjsなどの方が良いアプローチがあるのだろうかと思います。この例では

私は他のサービスを「通知」するために、初期化すると、私はEventEmitterを使用しているプロパティ_isInitを待っている:あなたはこのようReplaySubjectを使用することができ

class OneService { 

    private _isInit 
    private _initStatus = new EventEmitter() 

    constructor() { 
     Promise.all([ 
      Promise1(), //async task 
      Promise2(), //async task 
     ]) 
     .then(res => { 
      ... //doing stuff 
      this.init() //stuff finished, OneService is initiated 
     }) 
    } 

    init() { 
     this._isInit = true 
     this._initStatus.emit(this._isInit) 
    } 

    isInit() { 
     return new Promise(resolve => { 
      if (this._isInit) 
       resolve() 
      else { 
       this._initStatus.subscribe(() => { 
        resolve() 
       }) 
      } 
     }) 
    } 
} 

class anotherService { 

    constructor(myService: OneService) { 
     this.myService.isInit().then(() => { 
      ... //doing stuff 
     }) 
    } 

} 

答えて

2

:たぶん

class OneService { 

    public valueStream = new ReplaySubject(); 

    constructor() { 
     Promise.all([ 
      Promise1(), //async task 
      Promise2(), //async task 
     ]) 
     .then(res => { 
      ... //doing stuff 
      this.valueStream.next(value) 
     }) 
    } 

} 

class anotherService { 

    constructor(myService: OneService) { 
     this.myService.valueStream.subscribe((value) => { 
      ... //doing stuff 
     }) 
    } 

} 
+0

あなたが始めることができるように、[BehaviorSubject](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/behaviorsubject.md)を使用することをお勧め初期化された=偽の値 –

+1

あまりにも、Behavioを使用することができますrSubjectですが、initの状態は少し余分なものかもしれません。ストリームが値を送出したという事実によって本質的にサービスが初期化されていることがわかります。 – glendaviesnz

関連する問題