Book Image

Mastering Reactive JavaScript

By : Erich de Souza Oliveira
Book Image

Mastering Reactive JavaScript

By: Erich de Souza Oliveira

Overview of this book

If you’re struggling to handle a large amount of data and don’t know how to improve your code readability, then reactive programming is the right solution for you. It lets you describe how your code behaves when changes happen and makes it easier to deal with real-time data. This book will teach you what reactive programming is, and how you can use it to write better applications. The book starts with the basics of reactive programming, what Reactive Extensions is, and how can you use it in JavaScript along with some reactive code using Bacon. Next, you’ll discover what an Observable and an Observer are and when to use them.You'll also find out how you can query data through operators, and how to use schedulers to react to changes. Moving on, you’ll explore the RxJs API, be introduced to the problem of data traffic (backpressure), and see how you can mitigate it. You’ll also learn about other important operators that can help improve your code readability, and you’ll see how to use transducers to compose operators. At the end of the book, you’ll get hands-on experience of using RxJs, and will create a real-time web chat using RxJs on the client and server, providing you with the complete package to master RxJs.
Table of Contents (11 chapters)

The reduce() operator


The reduce() operator lets you run a function to accumulate all the values of an Observable to generate a new Observable containing only one value (the accumulated value).

This operator has the following signature:

observable.reduce(accumulatorFunction,[initialValue]); 

The first parameter is optional and the second one is mandatory:

  • acc: This is an accumulated value
  • currentValue: This is the value used in this iteration
  • currentIndex: This is a zero-based index of this iteration
  • source: This is the observable used
  • accumulatorFunction: This is a function that is used to accumulate values from an observable. This function can receive up to four parameters:
  • initialValue: This is the initial accumulator

We can use this function to sum up all the values in an Observable containing numbers, as follows:

Rx.Observable 
    .of(1,2,3) 
    .reduce((acc,current)=>acc+current) 
    .subscribe((i)=>console.log(i)); 

In this example, we first create an Observable that will propagate three...