Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to emit a change in rxjs based on a value

Tags:

rxjs

rxjs5

I can get the observable to fire the value once. But I want it to occure whenever the value of the variable changes. Effectively I need a watcher. Which is what I thought the point of an observable was. To observe a value or state of things and update anything that was subscribed to it.

Anyways, here's the code

import { Component, OnInit } from '@angular/core';

var Rx = require('rxjs/Rx');

import { Subject } from "rxjs/Rx";

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  private testBool: boolean = false;
  private observable;

  constructor() {  

    this.observable = Rx.Observable.of(this.testBool);

    this.observable.subscribe(
      (value) => console.log(value)
    )
  }

  toggleBool() {
    this.testBool = !this.testBool;

  }

}

so whenever the value of this.testBool changes, I want the subscribe to get updated. In it's current state, I get one console log and then nothing. I click the button that updates the boolean but the observer subscriber never fires again.

Am I missing some crucial point and this isn't how I'm supposed to use this?

And I know that I can bind the observer to the button click, but that's not how I want to achieve this. This would be a service level example. So anything anywhere could update the value.

I've read about subjects but I'm still learning. So maybe I'm supposed to be doing something with that?

Thanks

like image 201
cphilpot Avatar asked Apr 27 '17 13:04

cphilpot


1 Answers

You want to subscribe and send a new value to the observable. In that case you will need a Subject. In this case we are using a BehaviorSubject, in a BehaviorSubject you can set a default value.

import { Component, OnInit } from '@angular/core';
import { BehaviorSubject } from "rxjs/Rx";

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  private testBool: boolean = false;
  private observable: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

  constructor() {  
    this.observable.subscribe((value) => console.log(value))
  }

  toggleBool() {
    this.testBool = !this.testBool;
    this.observable.next(this.testBool);
  }
}
like image 177
Robin Dijkhof Avatar answered Nov 14 '22 21:11

Robin Dijkhof