Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it "safe" to expose your RxJS Subjects to the "outside world"

I read this good article on Angular onPush Change Detection Strategy

at some potin he wrote:

It’s an anti-pattern to expose your subject to the outside world, always expose the observable, by using the asObservable() method.

but he doesn't explain why. Does this mean that I shouldn't do somthing like this?

export class ExampleComponent {

  public drawerTrigger$ = new Subject<{}>(); 
}

and in the HTML

  <button  class="hamburgher-button" type="button"
     (click)="drawerTrigger$.next($event)">
    <i >menu</i>
  </button>

if no, which is the proper way?

like image 840
ALGDB Avatar asked Sep 07 '18 12:09

ALGDB


1 Answers

In general, you shouldn't expose Subjects because this gives anyone using your service possibility to uncontrollably call drawerTrigger$.next() even in incorrect use-cases.

Even worst situations is that anyone can use drawerTrigger$.error() or drawerTrigger$.complete(). Subjects have internal state and if they emit error or complete the Subject is marked as stopped and will never ever emit anything. If you expose your Subject then you let anyone emit these notifications.

The officially recommended way of exposing Subjects from TypeScript classes is just forcing their types to Observable. You don't need to use asObservable() (RxJS itself doesn't internally use asObservable() anywhere in its codebase):

export class ExampleComponent {
  private drawerTriggerSubject = new Subject<{}>(); 
  public drawerTrigger$: Observable<{}> = this.drawerTriggerSubject;
}
like image 61
martin Avatar answered Oct 20 '22 17:10

martin