I am new to RxJS. I was reading about first operator and understood that it returns the first element from a list/array/sequence or the first element which matches the given predicate.
I have written the below code
new Observable<number[]>(s => {s.next([1,2,3,4]);}).pipe(first()).subscribe({
next: (response) => console.log(response) // prints [1,2,3,4]
})
I was expecting that since my observable is emitting an array and the first operator would only return the first value to the subscribe's next function and 1 would be printed. Instead the complete array is printed.
from([1,2,3,4]).pipe(first()).subscribe({next: (res) => console.log(res)}) // prints 1
This code works as expected.
How are these two blocks of code different? Can anyone please explain?
first
returns first emitted value. Your value is the whole array.
s.next([1,2,3,4])
is equivalent to of([1,2,3,4])
not from([1,2,3,4])
.
from
flattens the values from array and emits them separately, you can achieve the same by using mergeAll
before first