1

Help me understand this code, how output of of (1,2,3) is piped to map( x => x*x) though map( x => x*x) is sequenced 1st in code line and of (1,2,3) is sequenced 2nd

map(x => x*x) (of (1,2,3)).subscribe((value)=> console.log(`value : ${value}`))

same can be written as below, that I understand well, but not above one..

of(1,2,3).pipe(map(x => x*x)).subscribe((value)=> console.log(`value : ${value}`))

FYI, both are correct, and return value 1,4,9

in case you are trying same in editor, include below imports

import {of} from 'rxjs'
import {map} from 'rxjs/operators'

2 Answers 2

1

This is actually an example from RxJS documentation, and is explained above:

A Pipeable Operator is essentially a pure function which takes one Observable as input and generates another Observable as output. Subscribing to the output Observable will also subscribe to the input Observable.

So what this means is map(x => x*x) returns a kind of function, which takes one Observable as an argument and returns another Observable. Then we invoke that function with (of(1,2,3)) and get our final result, which is, in fact, equal to of(1,2,3).pipe(map(x => x*x))

Sign up to request clarification or add additional context in comments.

Comments

0

Its more of a JavaScript functionality. If you see function is called like foo()() or foo() ('hello') that means foo is returning another function, and parameter in second "()" like 'hello' in foo() ('hello') is passed to function returned by foo().

Example
save below code as sample.js, and execute it using node sample

foo()()                  // return undefined, as empty parameter ( parenthesis ) are passed though expecting one
foo()('hello')           // param 'hello' is passed to bar when it is returned inside foo
foo()('hello','world')   //both hello and world are passed, but only hello is printed, as bar expect only 1 param


function foo() {
    return bar
}


function bar (param) {
    console.log('bar : '+param)
}

Results

bar : undefined 
bar : hello 
bar : hello 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.