I'm somewhat familiar with basic RxJS concepts like Observables, Observers and Subjects but RxJS Notifications concept is completely new to me.
What is it for? When should I use it?
RxJS tap() operator is a utility operator that returns an observable output that is identical to the source observable but performs a side effect for every emission on the source observable.
Tap is designed to allow the developer a designated place to perform side effects. While you could perform side-effects inside of a map or a mergeMap , that would make their mapping functions impure, which isn't always a big deal, but will make it so you can't do things like memoize those functions.
The pipe method of the Angular Observable is used to chain multiple operators together. We can use the pipe as a standalone method, which helps us to reuse it at multiple places or as an instance method.
The documentation you quoted mentions :
This class is particularly useful for operators that manage notifications, like
materialize
,dematerialize
,observeOn
, and others. Besides wrapping the actual delivered value, it also annotates it with metadata of, for instance, what type of push message it is (next
,error
, orcomplete
).
So the question turns out to be about use cases for materialize
and the like.
Basically, you use materialize
to get meta-information about the dataflow without incurring into the associated side-effects (an error incurring in a stream for example propagates, a stream which completes can lead to the completion of other streams etc.). dematerialize
allows to restore the side-effects.
Here are uses case from former SO questions :
A use case: as errors or completions are propagated immediately, you can't for example delay them. To do so, you can try this approach:
// sample stream
interval(500).pipe(
mapTo('normal value'),
// sometimes value, sometimes throw
map(v => {
if (randomInt() > 50) {
throw new Error('boom!')
} else return v;
}),
materialize(),
// turns Observable<T> into Notification<Observable<T>>
// so we can delay or what you want
delay(500),
// and we need to do some magic and change Notification of error into
// Notification of value (error message)
map(n => n.hasValue? n : new Notification('N', n.error.message, null)),
// back to normal
dematerialize()
)
// now it never throw so in console we will have
// `normal value` or `boom!` but all as... normal values (next() emmision)
// and delay() works as expected
.subscribe(v => console.log(v))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With