ago
ago

Reputation: 59

How to manage multiple observable in angular 7

I have a angualr 7 application, and totally 20 sensor data. I want to receive data every 5 seconds using observable for selected sensor id. For example;

var sensorId = ""; // dynamically selected from the web UI
var sensorData$ = interval(5000).pipe()
sensorData$.subscribe() // etc..

I'll select multiple sensor, and start to get data with subscribe using interval. How can I keep these observables? How can I manage it?

Also, I can add any sensor at any time.

Upvotes: 1

Views: 594

Answers (2)

Goga Koreli
Goga Koreli

Reputation: 2947

I would suggest using Subject and mergeMap.

As for explanation, you will have 1 Subject where you will emit new sensorIds when user selects one from the UI. Then you need to subscribe to that exact Subject and with the help of mergeMap you will have all of the sensor values in your subscribe method.

Lets look at demo code:

private sensorIdSubject = new Subject();

ngOnInit() {
  this.sensorIdSubject.pipe(
    mergeMap(sensorId => 
      interval(5000).pipe(switchMap(() => this.getSensorData(sensorId)))
  ).subscribe(sensorData => {
    // Every 5 second, each of the sensorIds that have been selected in UI will 
    // get sensor data and emit new value here in subscribe, because all of them
    // have been merged.
  })
}

public chooseSensor(sensorId) {
  this.sensorIdSubject.next(sensorId);
}

Does this fit? I will update my code according to your needs, just tell me in the comment section.

Upvotes: 1

Robert garcia
Robert garcia

Reputation: 591

You can use rxjs forkJoin

It combines all your observables into one which emits all the values, so you subscribe to the forkJoin emitted observable, you can add pipe operators to it etc

something like:

let sensors = forkJoin(observable1, observable2)

sensors.subscribe(
   sensorData => {
      // You receive an object with your observables data
   }
)

If you need to get a variable amount of observables which emits different values, you can use BehaviorSubject this way:

let sensors = new BehaviorSubject<Array<Observables<yourType>>([])

sensors.next([newArrayOfObservables])

sensors.subscribe(
    sensors$ => {
      sensor$.forEach(sensor => {
        sensor.subscribe( // Do your logic)
      }
    }
)

This way you can add/remove observables, since ForkJoin only emits values when observables completes it only emits values once.

Again remember to manage your unsubscriptions.

Upvotes: 0

Related Questions