Demo:  last

The last is a filter operator that emits only the last value or the last value matching the optional condition, when specified.

last(); //Witout any condition

last(v => optionalCondition)

The last operator emits only after the source completes and throws an EmptyError if no match is found.

//Emits every .5 sec starting at .5 sec
const source = timer(500, 500).pipe(take(9));

//emits the last matched item after the source completes
const filterItems = last((v) => v%3==0 );

const output = source.pipe(filterItems).subscribe(v=>console.log(v))
What is happening ?

The operators first and last can filter both by position as well as by condition.

The last operator without a condition parameter is like takeLast(1):

  • It will emit only the last item from the source when the source completes.

Secondly, the last operator can also take a boolean condition.

  • Where it will keep updating the last matching source item in it's buffer.
  • And, emit the same as the source completes.

Importantly, if the operator could not find a match to emit:

  • It will throw an "EmptyError" when the source completes.

Coming to our demo, the source emits 9 numbers:

  • Starting with 0, 1, 2 and continuing upto 8.
  • But, as we are interested only on the last number divisible by 3.
    • We have piped in our source into the last operator with the desired condition as shown.
  • For this, we will only get the last matching value 6 in our output, as the source completes.