Avoiding External State Using Observable Pipelines
Understand how to eliminate external state issues in RxJS observable pipelines by encapsulating data within the pipeline using operators such as scan. This lesson helps you build predictable concurrent programs and avoid state-related bugs by managing state internally rather than externally.
We'll cover the following...
We'll cover the following...
Example: Counting even ticks with a set interval
In the following example, we count the even numbers that interval has yielded so far. We do that by creating an Observable from interval ticks and increasing evenTicks when the tick we receive is an even number:
const Rx = require('rx');
var evenTicks = 0;
function updateDistance(i)
{
if (i % 2 === 0)
{
evenTicks += 1;
}
return evenTicks;
}
var ticksObservable = Rx.Observable
.interval(1000)
.map(updateDistance)
ticksObservable.subscribe(function()
{
console.log('Subscriber 1 - evenTicks: ' + evenTicks + ' so far');
});
Creating Observables from interval ticks
This is the output we get after the program has been running for four seconds:
Subscriber 1 - evenTicks: 1 so far
Subscriber 1 - evenTicks: 1 so far
Subscriber 1 - evenTicks: 2 so far
Subscriber 1 - evenTicks: 2 so ...