1

What is the difference between subscribing to subject and subscribing to asObservable?

What is the difference between the following?

 this.subject.subscribe((data) => this.datas.push(data));

 this.subject.asObservable().subscribe((data) => this.datas.push(data));

Seems like both are same!

mx_code
  • 2,441
  • 1
  • 12
  • 37
  • 1
    Does this answer your question? [When to use asObservable() in rxjs?](https://stackoverflow.com/questions/36986548/when-to-use-asobservable-in-rxjs) – insertusernamehere Mar 24 '21 at 13:22

1 Answers1

2

From the subscription side, there is no difference; emissions are received exactly the same.

asObservable() is used to hide the Observer behavior from consumers, preventing them from nexting values into the subject.

In angular, you'll see this in a lot services where you want consumers of the service to have access to the emitted values, but you don't want them to be able to call .next on the subject:

class SomeService {
    private subject$ = new Subject();
    public observable$ = this.subject$.asObservable();
}
BizzyBob
  • 12,309
  • 4
  • 27
  • 51