Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS Observables - multiple subscribers getting reference to same object

I've made an angular service to share state data across multiple components in my application. In order to share, it has a BehaviorSubject that can be subscribed to

export class DesignerService {
  private selectedFieldBehavior: BehaviorSubject<FormField> = new BehaviorSubject(this.selectedField);

  getSelectedField(): Observable<FormField> {
    return this.selectedFieldBehavior.asObservable();
  }
}

Multiple components subscribe to this via the getSelectedField() method. When I use next() to send a new object ( this.selectedFieldBehavior.next({ object }) ) , if any component subscribing to it modifies a property, all the subscribing components see that modification without notifying the service (like it's sending a reference instead of a copy), thus allowing the individual subscribers to modify each other's data

I've done a bit of work with angular/redux in the past, and I thought they promoted one-way dataflow and immutability. Reducers were the only way to modify the state, and then changes were propogated downwards to the subscribing components. What I currently have will allow child component to modify whatever they want. I'm not super experienced with building large angular apps that require state management. Am I mis-understanding how state management should work?

like image 811
Will Avatar asked Aug 04 '26 04:08

Will


1 Answers

You can change your method a bit to return a clone

getSelectedField(): Observable<FormField> {
  return this.selectedFieldBehavior.asObservable().map(obj=>Object.assign({},obj));
 }
like image 166
Fan Cheung Avatar answered Aug 05 '26 19:08

Fan Cheung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!