π Codes: finish custom observables.
- An observable = a data source.
- Observable patterns β observable β- stream β- observer
- Observer (in previous codes, you subscribe something to the event from observable) β 3 type of data received (3 hooks): Handle data, Handle error, Handle completion.
- Observables are contracts to which you subscribe to be informed about the changes in data.
There are several ways to create an observable from rxjs package.
All observables provided by Angular β no need to import from "rxjs" + no need to unsubscribe().
You rarely build your own observable β use the ones given by angular or somewhere else. Below are just for more understanding how to do so if you want!
Create manually
interval()
If we send HTTP request β we usually get .
There are some observables can be completed β what we will do when it happens?
Cancled due to an error IS DIFFERENT than it completes! β complete function in
.subscribe()
is not executed when there is an error!Operators are the magic features of the RxJS library turn observables β awesome construct!
Example: we wanna add "Round" before the number emiited (Round 1, Round 2,....) β an old option is to add "Round" in the
.subscribe()
function. β We can do that before theh subscription using Operators! β .pipe()
comes in!We need a transformation of the received data before you subscribe β using operators.
With
.pipe()
, we can apply 1 or more operators inside it!π Codes for this section.
Instead of using
EventEmitter
(from @angular/core
), to emit and subscribe event between components, we can use a subject!Unlike normal observable (you can created) β
.next()
is used INSIDE the observable (when you created it) β subject is different: we can call .next()
outside the observable!There are also other subclasses for Subjects:
BehaviorSubject
, ReplaySubject
,...GOOD PRACTICE:
- Don't use
EventEmitter
, useSubject
!!!! β don't forget to unsubcribe to Subect when you don't need them. β by storing the subscription + then unsubscribe(). - Only use Subject to communicate across components through services/mechanisms where you in the end subscribe to somewhere!
- Not subscribe to an event which probably is an output if you do plan to subscribe manually!
- ONLY USE
EventEmitter
on the@Output
property!! β EventEmitter gets cleaned auto (no need unsubscribe)