[WP] 23.06.2023 | subjects

 

fig 1.1 BehaviorSubject abstraction marble diagram

 

    It is high time to write another part of angular basics revision. Last time i mentioned Subject object. It is also worth to describe other ‚special’ cases of Subject. The first is behavior subject. It is part of powerful tool for reactive programming called rxjs. When writing angular version of exchange app or mars-rover-photos app I was using behavior subject in following way. Start with declaring behavioral subject private field within your service. The following example ilustrates this step:


 private myDataSubject: BehaviorSubject<any> = new BehaviorSubject<any>(
    null
  );
 

 it will declare new private field with myDataSubject name and BehaviorSubject type. The value within <> braces is called type parameter and is a part of TypeScript generic types. In this case it would describe the type of values emited by this subject. on the right side of the assignment statement we can see basic javascript instatiation with new keyword. It is initialized to null value. It is one of characteristics of behavior subject that it have to be explicitly initialized with value .

The next step is to create new observable using asObservable() construction operator and declare it as a service class field. By convention class properties which are observables should be marked with $ to differenciate the from regular fields.


  roverData$ = this.roverDataSubject.asObservable();

fig 1.2 short description of different rxjs subjects variants



 

    From now on .next(), .complete(), .error() methods may be used on newly created BehaviorSubject object(myDataSubject). We can create service class method and use BehaviorSubjectMethod within. After that service class method may be shared with other parts of application via dependency injection and thus they get a way to pass values to subject. Another example of .next() application may be passing data within .pipe() method or observer function. Each app component with above service injected may subscribe to roverData$ observable and react to its value changes. Last but not least BehaviorSubject always remember last value which have been provided. it may be checked anytime with .get() method.

There are types of subject similar to BehaviorSubject. Replay subject remebers all values that recieves within an array. Async subject remebers multiple items/operations but only after the have been fullfilled.

Aloha

g-marcin
                      

Komentarze

Prześlij komentarz

Popularne posty z tego bloga

15.07.2024 | simplicity

[WP] 05.06.2023 | angular-intro