Royi Namir
Royi Namir

Reputation: 148664

Angular2 sibling communication via Observable -Best practice?

I have a simple app which involves sibling components communication. this is done via Observable.

This is done by a service :

@Injectable()
export class SharedService {

  private caseNumber = new Subject<string>();  

  caseNumber$ = this.caseNumber.asObservable(); //components subscribe to this <--

  publishData(data: string) {
    this.caseNumber.next(data);
  }

But I can also do it in a different way :

@Injectable()
export class SharedService {

  caseNumber$ = new Subject<string>();  //components subscribe to this <--

  publishData(data: string) {
    this.caseNumber$.next(data);
  }

Question

What are the differences between those two approaches and which one should I use?

Upvotes: 2

Views: 128

Answers (1)

n00dl3
n00dl3

Reputation: 21574

Subjects are Read-Write Observables, they are used when you are creating Observable imperatively (not from event, callback, etc), all the logic of the broadcasting is internal to your class / service.

Usually it is a better practice to expose observables instead of subjects, except if you need your external component to modify it.

But, note that would be weird to modify it through the Subject instead of some public method, as it is the service which is responsible of maintaining the Subject, it might lead to unexpected side-effect as the broadcasting is made imperatively.

Consider this service :

class FooService{
  foo = new Subject<Foo>();
  bar:boolean=false;
  setFoo(foo:Foo){
    this.bar=true;
    this.foo.next(foo);
  }
  doStuff(){
    if(this.bar){
      //do stuff
    }
  }
}

if an object emitted a value through fooService.foo.next(new Foo());, the bar property (some state) would not be updated, so there might be a problem when calling fooService.doStuff(). That's why it might be better to expose an Observable to the outside world, and keep your Subject private. But note that, as would say people from the python world, "we are all consenting adults".

A good article on the topic "should I use a Subject or an Observable ?".

Upvotes: 2

Related Questions