Подтвердить что ты не робот

Использование Observable для обнаружения изменения переменной

Я думаю, что неправильно понимаю, как предполагается использовать Observables. Я хочу добавить значение, и когда значение изменится, оно должно испустить новое значение. Я думал, что это то, для чего они нужны, но все учебники и документы, похоже, не делают этого, но в то же время я всегда вижу, что они применяются таким образом. Например, в angular, когда вы подписываетесь на "FirebaseListObservable", когда значение в firebase изменяется, он запускает моментальный снимок в подписке. Я хочу сделать это для своей переменной. Скажем, у меня просто есть строковая переменная, и когда она изменяется, она отключает любые подписки.

4b9b3361

Ответ 1

Как правило, у меня были бы наблюдаемые в службах, которые подписались на компоненты, но я собрал их все в одном классе для удобства этого ответа. Я перечислил комментарии, объясняющие каждый шаг. Надеюсь, это поможет.:)

import { Subject } from 'rxjs/Subject';

export class ClassName {
    // ------ Creating the observable ----------
   // Create a subject - The thing that will be watched by the observable
   public stringVar = new Subject<string>();

   // Create an observable to watch the subject and send out a stream of updates (You will subscribe to this to get the update stream)
   public stringVar$ = this.stringVar.asObservable() //Has a $ 

   // ------ Getting Your updates ----------
   // Subscribe to the observable you created.. data will be updated each time there is a change to Subject
   public subscription = this.stringVar$.subscribe(data => {
         // do stuff with data
         // e.g. this.property = data
   });

  // ------ How to update the subject ---------
   // Create a method that allows you to update the subject being watched by observable
   public updateStringSubject(newStringVar: string) {
     this.stringVar.next(newStringVar);
   }
   // Update it by calling the method..
   // updateStringSubject('some new string value')

   // ------- Be responsible and unsubscribe before you destory your component to save memory ------
   ngOnDestroy() {
     this.subscription.unsubscribe()
   }
}

Ответ 2

Попробуйте использовать ReplySubject. Я использовал typescript, angularfire для объяснения в приведенном ниже примере кода

export class MessageService {
  private filter$: ReplaySubject<any> = new ReplaySubject(1);

  getMessagesOfType():FirebaseListObservable<any>{
   return this.af.database.list(this.messagesPath, {
    query: {
      orderByChild: 'type',
      equalTo: this.filter$
    }
  });
  }
  getClosedMessage(): void {
    this.filter$.next('closed');
  }
  getOpenMessage(): void {
    this.filter$.next('open');
  }
}

// in some other class
// MessagesSubject is assigned to messageService 
this.messageService.getMessagesOfType().subscribe((listOfMessages)=>{
 // this list will be updated when the this.filter$ updated see below functions
 console.log(listOfMessages); 
});
// update this.filter$ like this to get 
this.messageService.getClosedMessage();
// to get open messges in 
this.messageService.getOpenMessage();