Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS6 asObservable() needed on a Subject?

When is asObservable() needed on a Subject (e.g. BehaviorSubject) to get a observable of the subject? The subject isself can be casted to an Observable as well.

Questions

  1. What are the technical differences between name1$ and name2$?
  2. Which one should be used (name1$ or name2$)?

Code Sample

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs';

export class Person {
  private nameSubject: BehaviorSubject<string> = new BehaviorSubject<string>('lorem');

  public get name1$(): Observable<string> {
    return this.nameSubject.asObservable();
  }

  public get name2$(): Observable<string> {
    return this.nameSubject;
  }

  public setName(value: string): void {
    this.nameSubject.next(value);
  }
}

Thank You for your answers in advance!

like image 874
Horace P. Greeley Avatar asked Nov 29 '19 08:11

Horace P. Greeley


1 Answers

In general, it's recommended to use asObservable() only when using RxJS in JavaScript. With TypeScript you can use just type casting and it won't let you call next() and so on.

private nameSubject: BehaviorSubject<string> = new BehaviorSubject<string>('lorem');
public nameSubject$: Observable<string> = this.nameSubject;

This is the officially recommended way of turning Subjects to Observables in TypeScript.
For details see https://github.com/ReactiveX/rxjs/pull/2408#issuecomment-282077506.

like image 107
martin Avatar answered Sep 24 '22 12:09

martin