Reducing

Now that the array of words is being flattened into separate events, we need some way of handling each of these smaller, “inner” events. Effectively, two different streams of data are going on. One is the same stream from before: every keystroke triggers an event containing the current content of the textbox. The new stream is smaller (and finite), containing an event for every word in the textbox. Mixing these two would be problematic—the view rendering function wouldn’t know whether a new word is a continuation of the inner stream, or represents the beginning of a new event from the original stream. There’s no way to know when to clear the page without adding obtuse hacks to your code.

Instead of intermingling two different streams, we can create an inner observable to represent the stream of individual words. mergeMap makes this easy. If mergeMap’s function returns an observable, mergeMap subscribes to it, so the programmer only needs to be concerned about the business logic. Any values emitted by the inner observable are then passed on to the outer observable. This inner observable neatly completes because there is a finite amount of data to process (unlike the event-based outer observable). The inner observable here uses the from constructor, which takes any unwrappable value (arrays, promises, other observables), unwraps that value, and passes each resulting item along as a separate event. Here, split returns an array, so the observable emits a new event for each string in the array.

 mergeMap(wordString =>
 // Inner observable
 from​(wordString.split(​/​​s​​+/​))
  .pipe(
  map(pigLatinify),
  reduce((bigString, newWord) => bigString + ​' '​ + newWord, ​''​)
  )
 )

The inner observable is created using the from constructor, which takes an iterable, such as an array, and creates an observable containing all of the items in that iterable. In this instance, from passes on each word individually to the rest of the stream. The first operator is the same map we used before, passing each word to Pig Latin translation function. At the end of the inner observable is a new operator: reduce. Reduce works just like the regular JavaScript version does: given a collection of data, it applies a collection function to each item. When it’s finished processing every item in the collection, it emits the final value down the stream (in this case, to the subscriber). It also takes a second argument—the initial value (an empty string).

A simple reduce to sum all of the numbers in an observable stream looks a lot like the array example above (using an initial of value 0):

 from​([1,2,3])
 .pipe(
  reduce((accumulator, val) => accumulator + val, 0)
 )
 .subscribe(console.log); ​// Logs `6` once
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.239.166