How to use BehaviorSubject in an Ionic app with many variables?

Hi,
my question is about BehaviorSubject:

I’ve defined them in this way:

public mobileLatitude: BehaviorSubject<number> = new BehaviorSubject<number>(null);
public mobileLongitude: BehaviorSubject<number> = new BehaviorSubject<number>(null);
public mobileAltitude: BehaviorSubject<number> = new BehaviorSubject<number>(null);
public mobileHeading: BehaviorSubject<number> = new BehaviorSubject<number>(null);
public mobileSpeed: BehaviorSubject<number> = new BehaviorSubject<number>(0);
public mobileDataTimestamp: BehaviorSubject<number> = new BehaviorSubject<number>(null);

And I change them in this way:

this.mobileSpeed.next(location.speed);
this.mobileLatitude.next(location.latitude);
this.mobileLongitude.next(location.longitude);
this.mobileAltitude.next(location.altitude);
this.mobileDataTimestamp.next(tmstp);

Now, is it sure that they are modified in the order I wrote them?
That is when I manage the last Behaviour (mobileDataTimestamp), are the previous Behaviours already updated?

this.mobileDataTimestamp.subscribe((value) => {
....
});

The alternative is to use an object Location into a BehaviorSubject.
But is it possible to use an object into a BehaviorSubject?

Thank you very much

cld

Yes definitely u can

Just try and make your life easier

Key principle is keep it DRY: dont repeat yourself!

In my experience, yes, although I wouldn’t ever suggest writing anything that depends on that.

A much better choice.

As @Tommertom already pointed out, yes. I’d like to add one caveat: because of JavaScript’s laissez-faire ownership rules, your app code is responsible for defining and obeying semantics for modification of objects passed around. If you subscribe to that subject in one place, and modify something in the object you get, that modification affects everybody else that has a reference to that object.

1 Like

Great addition.

A big headbanger for me the other day playing with NGRX. Thank god for freeze tools in dev to discipline and punish me at dev-time. Other headbanger was doing proper cloning with deep object structures… If you need to alter the object, you need to clone first, which can be done using Object.assign but only if it is a shallow object.