Rxjs
A Better Way to Learn RxJS & Observables

Creating an Observable from a Subject

PRO

In the RxJS world it's considered best practice to only expose Subjects to the parts of your application that would add new data into the Observable sequence. This is the same idea behind only allowing write access to certain parts of your application, private and public class members, etc.

To create an Observable from a Subject, you can simply invoke asObservable on any Subject:

let currentUserSubject = new BehaviorSubject<string>('Eric');
let currentUser = currentUserSubject.asObservable();

We now have a new variable called currentUser that is an Observable of currentUserSubject's observable sequence. To see how this works, lets subscribe to the currentUser observable and then add some data to the currentUserSubject:

let currentUserSubject = new BehaviorSubject<string>('Eric');
let currentUser = currentUserSubject.asObservable();

currentUserSubject.subscribe((val) => {
    console.log(val)
})
// => 'Eric'

currentUserSubject.next('hello');
// => 'hello'

Note that if you try and call currentUser.next(), it will throw an error because Observables can only observe a sequence - thus providing you with read-only access to the currentUserSubject!

Real world example

In the video above we demonstrated how you can use a BehaviorSubject with an accompany Observable for storing & sharing data within an Angular Service, and then injecting it into other services and components. Below is the live demo of the running code: