Reputation: 13
Hello in Rxjs documentation I see this code:
first()(of(1, 2, 3)).subscribe((v) => console.log(`value: ${v}`));
// Logs:
// value: 1
I knew it's like Just as [1, 2, 3].map(x => x * x)
, but I would know if we can do the same with native JavaScript if so please give me an example ?
my question is :
I don't understand how first()(of(1, 2, 3)) can you explain me how this code return an observable with an operator and source ? I knew operator is the first() and source is of() but how they're merged together inside a new observable ?
Thank you
Upvotes: 1
Views: 134
Reputation: 21638
It is not the intended way of using the first operator, of(1, 2, 3).pipe(first())
is how it is meant to be used. It works because first returns a function that takes an observable in as a parameter.
Upvotes: 0
Reputation: 14740
Executing first()
returns a function which takes an observable and returns an observable.
Let's break down that line of code so maybe it's easier to understand.
first()(of(1, 2, 3)).subscribe((v) => console.log(`value: ${v}`));
The following code is equivalent to the above line:
const myFunction = first();
const source$ = of(1, 2, 3);
const output$ = myFunction(source$);
output$.subscribe(v => console.log(`value: ${v}`)); // value: 1
So, myFunction
is a function, specifically an OperatorFunction
that essentially looks like this:
function myFunction(source: Observable): Observable { }
How they're merged together inside a new observable?
They aren't really "merged together", first()
generates the function and then you're executing that function with source$
as the input parameter.
The resulting output$
is another observable that can be subscribed to.
Upvotes: 4
Reputation: 6289
first()
is an operation that runs on (of(1, 2, 3)
. The result will be 1
, since the first value of 1, 2, 3
is 1
, and that's exactly what the first()
operation does - it takes the first value. This observable is then subscribed to with the chaining on of the .subscribe()
- and thus, the value 1
is what ends up being printed to the console.
Upvotes: 1