Categories
JavaScript

Using Rxjs Join Creation Operators to Combine Observer Data

RxJS is a library for reactive programming. Creation operators are useful for generating data from various data sources to be subscribed to by Observers.

In this article, we’ll look at some join creation operators to combine data from multiple Observables into one Observable. We’ll look at the combineLatest, concat, and forkJoin operators.

combineLatest

We can use the combineLatest to combine multiple Observables into one with values that are calculated from the latest values of each of its input Observables.

It takes 2 or more Observables as arguments or one array of Observable as an argument. It returns an Observable that emits values that are an array of values of all the Observables that were passed in.

combineLatest also takes an optional project function, which takes an argument of all values that would be normally be emitted by the resulting Observable, then we can return what we want given the values in that function.

combineLatest works by subscribing to each Observablke in order and whenever an Observable emits, collect the emitted data into an array of the most recent values of each Observable. Then the array of values gets emitted by the returned Observable.

To ensure that the output array always has the same length, combineLastest wait for all input Observables to emit at least once before it starts emitting results. If some Observable emits values before others do, then those values will be lost.

If some Obsetrvables doesn’t emit by completes, then the returned Observable will complete without emitting anything since that one didn’t emit any value.

If at least one Observable was passed into combineLatest and all of them emitted something, then the returned Observable will complete when all the combined streams complete. In this case, the value will always be the last emitted value for the Observables that completed earlier.

For example, we can use it as follows:

import { combineLatest, of } from "rxjs";
const observable1 = of(1, 2, 3);  
const observable2 = of(4, 5, 6);  
const combined = combineLatest(observable1, observable2);  
combined.subscribe(value => console.log(value));

Then we get:

[3, 4]  
[3, 5]  
[3, 6]

since observable1 emitted all its values before observable2 did.

We can also use the optional second argument to do some calculations:

import { combineLatest, of } from "rxjs";  
import { map } from "rxjs/operators";
const observable1 = of(1, 2, 3);  
const observable2 = of(4, 5, 6);  
const combined = combineLatest(observable1, observable2).pipe(  
  map(([a, b]) => a + b)  
);  
combined.subscribe(value => console.log(value));

In the code above, we got the sum of the values. Then we get:

7  
8  
9

These are the sum of each entry that we have before.

concat

We can use the concat operator to take multiple Observables and return a new Observable that sequentially emits values from each Observable that were passed in.

It works by subscribing to them one at a time and merging the results in the output Observable. We can pass in an array of Observables or put them directly as arguments. Passing in an empty array will result in an Observable that completes immediately.

concat doesn’t affect Observables in any way. When an Observable completes, it’ll subscribe to the next one an emit its values. This will be repeated until the operator runs out of Observables.

merge operator would output values from Observables concurrently.

If some input Observable never completes, concat will also never complete and Observables follows them will never be subscribed. If some Observable completes without emitting any values, then it’ll be invisible to concat .

If any Observable in the chain emit errors, then the error will error immediately. Observable that would be subscribed after the one that errors will never be subscribed to.

We can pass in the same Observable subscribe to the same one repeatedly.

For example, we can use it as follows:

import { concat, of } from "rxjs";
const observable1 = of(1, 2, 3);  
const observable2 = of(4, 5, 6);  
const concatted = concat(observable1, observable2);  
concatted.subscribe(value => console.log(value));

Then we get:

1  
2  
3  
4  
5  
6

as we expect.

forkJoin

forkJoin accepts an array of Observables and emits an array of values in the exact same order as the passed array or a dictionary of values in the same shape as the passed dictionary.

The returned Observable will emit the last values emitted of each Observable. For example, we can write:

import { forkJoin, of } from "rxjs";
const observable1 = of(1, 2, 3);  
const observable2 = of(4, 5, 6);  
const joined = forkJoin(observable1, observable2);  
joined.subscribe(value => console.log(value));

Then we get [3, 6] .

We can also pass in an object with Observables as properties:

import { forkJoin, of } from "rxjs";
const observable1 = of(1, 2, 3);  
const observable2 = of(4, 5, 6);  
const joined = forkJoin({ observable1, observable2 });  
joined.subscribe(value => console.log(value));

Then we get:

{observable1: 3, observable2: 6}

Conclusion

The combineLatest, concat, and forkJoin operators are very useful for combining emitted data from multiple Observables.

With combineLatest, we can combine emitted data from multiple Observables and get arrays of values that are formed by the latest values emitted by each Observable that we passed in.

The concat operator subscribes to each Observable that we passed in sequentially and return an Observable that emits values from each sequentially. If an error occurs in any Observable, an error will be emitted by the returned Observable.

Finally, the forkJoin operator returns an Observable that get the latest values from each Observable and emits the value as an object or an array depending if you passed in a dictionary of Observables or an array of Observables.

Categories
JavaScript JavaScript Basics

What Does the Percent Sign Mean in JavaScript?

JavaScript has many operators. One of them is the percent sign: %. It has a special meaning in JavaScript: it’s the remainder operator. It obtains the remainder between two numbers.

This is different from languages like Java, where % is the modulo operator.

In this piece, we’ll look at the difference between the modulo and the remainder operator.


Modulo Operator

The modulo operator works like the mod operator in math. It’s a basic part of modular arithmetic, which works like the clock. The number wraps around to something smaller than the given value, when it’s bigger than it.

For example, a clock has 12 hours. We represent that in math with by writing x mod 12 where x is an integer. For example if x is 20 then 20 mod 12 is 8 since we subtract 12 until it’s between 0 and 11.

Another example would be a negative number for x. If x is -1, then -1 mod 12 is 11 since we add 12 to it to make it within between 0 and 11.

12 mod 12 is 0 since we subtract 12 from it until it’s within the same range.

The operand after the mod can be positive or negative.

If the right-hand operand is negative, then the range of it must be from the negative number plus 1 to 0.

For example, if we have 1 mod -3 . Then we subtract 3 from it to get -2 .

To see more properties of modular arithmetic, check out this article for modular arithmetic and this article for the modulo operator from Wikipedia.

The JavaScript percent sign doesn’t do modular arithmetic. It’s used for finding the remainder when the first operand is divided by the second operand.


Remainder Operator

This is what JavaScript’s percent sign actually means. For example, if we write:

10 % 2

we get 0 since 10 is evenly divisible by 2.

If the first operand isn’t even divisible by the second operand, then we get a non-zero remainder. For example, if we have:

10 % 3

Then we get 1 since 10 divided by 3 has a remainder of 1.

Since the percent sign is a remainder operator, it also works if either number is negative. For example, if we have:

10 % -3

Then we get 1 because the quotient is -3 and the remainder is 1.

On the other hand, if we write:

-10 % 3

Then we get -1 because the quotient is -3 and the remainder is -1.


Bitwise Operator for Doing Modular Arithmetic

We can use the >>> operator, which is the zero left shift operator, to compute a number modulo 2 to the 32nd power.

The zero left shift operator shifts right by pushing zero in from the left and the rightmost one falls off the shift.

For example, if we write:

2**32 >>> 32

Then we get 0 since we pushed 32 zeroes in from the left, which pushed all the ones out.

Writing 2**32 >>> 0 is the same as 2**32 >>> 32.

If we write 2**32 + 1 >>> 32 then we get 1 since we added the 33rd bit on the left with the value 1, then we pushed in 32 zeroes from the left, leaving only 1 bit left.


Using Typed Array for Modulo Operation

We can also use typed arrays like the Uint8Array, Uint16Array, and Uint32Array for modulo operations since each entry can only be 0 to 2**8–1, 0 to 2**16–1, or 0 to 2**32–1respectively. The U in the first character of the name means unsigned.

In each example below, we create a typed array with one entry, then we assign various values to it to compute x mod 2**8 , x mod 2**16 and x mod 2**32 respectively.

For example, if we write:

const arr1 = new Uint8Array(1);  
arr1[0] = 2**8;  
console.log(arr1[0]);  
arr1[0] = 2**8 + 1;  
console.log(arr1[0]);

Then we get that the first console.log gives us 0 and the second console.log gives us 1 since the entries are wrapped to be between 0 and 2**8 - 1.

Likewise, we can do the same thing with the other kinds of typed arrays as follows:

const arr1 = new Uint16Array(1);  
arr1[0] = 2**16;  
console.log(arr1[0]);  
arr1[0] = 2**16 + 1;  
console.log(arr1[0]);

And:

const arr1 = new Uint32Array(1);  
arr1[0] = 2**32;  
console.log(arr1[0]);  
arr1[0] = 2**32 + 1;  
console.log(arr1[0]);

Then we get the same results as the first example.


Write a Modulo Function with JavaScript

If we actually want to do modular arithmetic with JavaScript, we have to write our own modulo function.

One example would be this:

const mod = (a, b) => ((a % b) + b) % b

It wraps the results of a % b to be within 0 and b — 1 or b+1 and 0 if b is negative by adding a % b to b. a % b is always less than a since it’s the remainder, but it might not be within the range of 0 and b — 1 or b+1 and 0and 0 if b is negative so we add b to it.

If we write:

console.log(mod(1, 12));  
console.log(mod(13, 12));  
console.log(mod(13, -12));

Then we should get:

1  
1  
-11

This is what we expect.

In JavaScript, the percent sign is the remainder operator. It gets us the remainder of the number when we divide the left operand by the right operand. To do real modulo operations with JavaScript, we have to write our own function to do it or we can use a typed array to do it since it wraps the value to be within the given range.