Map

map() transforms incoming data using the provided function.
The function can be a simple synchronous function, in which case it should take only one argument:
  /*!*/import { source, spread, map } from '@connectv/core';

let a = source();

a.to(spread())             //--> spread incoming array as multiple emissions
/*!*/ .to(map(x => x * 2))      //--> multiply each number by 2
 .subscribe(console.log);  //--> log it

a.send([1, 2, 3, 4]);
a.send([10, 20, 30, 40]);
Or it can be an asynchronous function, in which case it should take a callback as second argument:
  /*!*/import { source, spread, map } from '@connectv/core';

let a = source();

a.to(spread())
/*!*/ .to(map((x, done) => {
/*!*/   setTimeout(() => done(x * 2), x * 100);  //--> multiply by 2 and respond after a bit
/*!*/ }))
 .subscribe(console.log);

a.send([4, 2, 1, 3, 8, 5, 7]);              //--> notice how the order is not preserved


Error handling

In a sync map function, you can simply throw the errors that occur:
  import { source, map } from '@connectv/core';

let a = source();

a.to(map(x => {
/*!*/   if (x == 2) throw new Error('No 2s pls.');
   return x + 3;
 }))
 .subscribe(
   console.log,    //--> log the ok values
/*!*/   error => {      //--> handle the errors
/*!*/     console.log('ERROR:: ' + error.original.message);
/*!*/   }
 );

a.send(5);
a.send(2);
Async map functions are provided with an error callback as their third argument, to which they should pass errors that occur:
  import { source, map } from '@connectv/core';

let a = source();

let brokenPromise = new Promise((resolve, reject) => {
  reject('For no particular reason');
});

/*!*/a.to(map((x, done, error) => {
/*!*/  brokenPromise
/*!*/    .then(() => done(x))
/*!*/    .catch(e => error(e));
/*!*/}))
.subscribe(
  () => {},                            //--> ignore good values
/*!*/  e => console.log(e.original.message) //--> log the errors
);

a.send();


Function purity

Sync map functions MUST be pure, i.e. without any side-effects. This simply means that running them with the same input should always result in the same output. Impurity of a sync map function might result in unpredictable behavior of the flow.

If your transformation is not pure, then wrap it inside an async map function. Fore more details on this, you can read this entry.

Further reading




Copied to Clipboard!