Search code examples
angularrxjsobservablesubscription

RxJS Observable not triggering on change in Angular Material


I am trying to perform an action as soon as the service i created is connected to his server. Currently im simply saving a connected: boolean which changes state on connection and connection lost, and return it as an observable.

With the subscribe i am only able to retrieve the initial state of the observable. The subscribe does not fire when the boolean changes its value (which it does).

Any help is appreciated.

app.component.ts (subscription)

ngOnInit() {
    this.moduleService.isConnected().subscribe(value => console.log(value)); 
  }

module.service.ts (injected in component)

isConnected(): Observable<boolean> {
    return of(this._mqttApi.isConnected());
  }

mqttApi.ts (boolean changes here)

connected: boolean = false;

onConnect(){
  connected = true;
}

onConnectionLost(){
  connected = false
}

public isConnected(): boolean{
  return this.connected;
}

Solution

  • In your module.service.ts you are only returning an observable that only emits once by using the of. What you need is a BehaviorSubject or Subject as the type for the connected property instead of a boolean inside your mqttApi.ts

    And then make that observable public with connected.asObservable() if you don't want services using this observable to make changes to the subject. Otherwise you could also make the subject/behaviourSubject public.

    And inside your methods you are calling connected.next(true|false)

    Something like this:

    connected: BehaviorSubject<boolean> = new BehaviorSubject(false);
    
    onConnect(){
      this.connected.next(true);
    }
    
    onConnectionLost(){
      this.connected.next(false)
    }
    
    public isConnected(): Observable<boolean>{
      return this.connected.asObservable();
    }