您的当前位置:首页Observable - SwitchMap

Observable - SwitchMap

2024-12-12 来源:哗拓教育
  1. HTTP Stream
    (1) the HTTP observables are cold (or not live), meaning that they will not start emitting values until we subscribe to them
    (2) these Observables only emit a single value or an error, and then after that they complete, so they are not long-lived Observables
    (3) in most cases, we don't have to remember to unsubscribe from these Observables, because they will complete after emission

  2. SwitchMap Operator of HTTP Stream
    Let's simulate a request that saves some user data, and then reloads some other data that is impacted by that server-side modification.


    image.png

Given this output, let's break this down step-by-step to see what the switchMap operator is doing in this scenario:

(1)The saveUser$ HTTP observable is said to be the source observable
(2)The output of the switchMap is the resultObservable$ constant, which we will refer to as the result observable
(3)if we don't subscribe to the result observable, nothing will happen
(4)if we subscribe to the result observable, that will trigger a subscription to the source Observable saveUser$
(5)once the source Observable emits, the source value emitted is then passed on to the function that we have passed to the switchMap operator
(6)that function needs to return an Observable, that might be built using the source value or not
(7)that returned observable is said to be the inner observable
(8)the inner observable is then subscribed to, and its output is then emitted also by the result observable
(9)when the source observable completes, the result observable also completes
So as we can see the switchMap operator is a great way of doing one HTTP request using the output of an initial request here, so this is one common way that we can use it.

  1. Long-lived streams
    (1)maybe the most noticeable thing here is that both streams never complete, they keep emitting values!
    (2)this type of streams will continue to emit new values (if a new value is available) until we unsubscribe from them

  2. SwitchMap Operator of long-live Stream


    image.png
    image.png

总结
Let's then summarize what we have learned so far: The switchMap operator will create a derived observable (called inner observable) from a source observable and emit those values.

When the source emits a new value, it will create a new inner observable and switch to those values instead. What gets unsubscribed from are the inner observables that get created on the fly, and not the source observable.

I hope this helps explain the operator, its name and some frequently used use cases for which you might want to use it (let me know in the comments).

显示全文