So, now that we know not honoring the unsubscribe function is bad, let's take a look at how it works. Let's jump back to our previous example and see how the take
function behaves.
The take function when invoked on an observable creates a new observable that will only produce a limited number of values based on the int value provided to it. In the case of the above example take(10)
will create an observable that only produces 10 values. How take operates is that when an observer subscribes to the observable that it produces, the observable then subscribes an observer to the source observable that it was created from. As each value is pushed to it's observer it increments an internal counter and then pushes the value on to it's subscriber. Once the counter reaches the specified count (in our case 10) the take observer unsubscribes from the source observable and invokes the onComplete
function on the observer listening to it. If at any time the subscriber unsubscribes from it, it simply unsubscribes from the source observable.
If you jump back one step on the invocation chain, you'll notice map(x => x*x)
. Map behaves very similarly to take, instead of incrementing a count and potentially completing as each value passes through, it simply transforms the value and pushes it on to it's subscriber. It will also correctly unsubscribe from it's source observable when it itself is unsubscribed from. The full observable chain from the example can be visualized as such:
Read full article from Random.next()
No comments:
Post a Comment