Reputation: 1858
I'm having trouble using the RXJS methods to get what I need.
this.tutorials$
.pipe(
map( data => data.map(item => item.id)), // returns [10,20,30,40]
last()
)
.subscribe( console.log ); // returns nothing. Isn't supposed to return 40?
I want to extract the last item of the array. What am I doing wrong? Is there a better way aside the last method?
Thanks.
Upvotes: 2
Views: 6038
Reputation: 6441
The last operator will only emit an item when the observable completes. I dont know what your tutorials$ observable does, but im guessing that is the reason why nothing is returned.
https://www.learnrxjs.io/operators/filtering/last.html
Also, rxjs operators operate on the sequence of emitted items, not of the emitted items themselves. If you simply want to extract he last value of that array, do it in the map() operator.
this.tutorials$
.pipe(
// will error on empty array, be more defensive here
map( data => data[data.length-1].id)
)
.subscribe( console.log ); // return 40, every time the tutorials$ emits
But i understand your confusion, i made the exact same mistake when i started using rxjs ...
Upvotes: 3
Reputation: 96889
There're two things you need to be aware of:
What is this.tutorials$
and does it complete? If it's just an Ajax request then you're fine because it completes right away but if it's a Subject on the other hand and you never call this.tutorials$.complete()
then this chain will never complete and thus last()
won't emit anything because it doesn't know when comes the last value.
As you mentioned map(...)
returns an array [10,20,30,40]
but last()
emits the last emission from its source Observable. Not the last item in an array. So you might in fact want to use just map(ids => ids[ids.length -1])
.
Upvotes: 1
Reputation: 16441
Your Observable is supposed to emit the array itself, not the elements of the array. Therefore you will not get the last item, instead you will get the whole array itself.
Modify your code as follows to get the last item in the array:
this.tutorials$
.pipe(
map( data => data.map(item => item.id)), // emit array
concatMap(array=>from(array)), // emit array elements
last() // get the last element
)
.subscribe( console.log );
Upvotes: 2