2

Can anybody explain me difference between last() and takeLast() methods ? As documentation tell:

last() - Emit the last element observed before complete signal as a Mono, or emit NoSuchElementException error if the source was empty. For a passive version use takeLast(int)

takeLast() - Emit the last N values this Flux emitted before its completion.

As for me it's the same. I can not understand the differences. Can someone explain me with a simple example? Thanks in advance

Kirill Sereda
  • 469
  • 1
  • 10
  • 25

1 Answers1

3

Kirill,

takeLast(int n) accepts integer indicating how many elements should be left in the stream Example:

Flux.just(1, 2, 3, 4)
        .takeLast(3)
        .subscribe(System.out::println);

Will result with

234

Meanwhile, last() method is only about the very last emitted element.

Flux.just(1, 2, 3, 4)
        .last()
        .subscribe(System.out::print);

The output is

4


Conclusion: takeLast(1) equals to last()

Stepan Tsybulski
  • 1,121
  • 8
  • 18
  • 4
    "Conclusion: takeLast(1) equals to last()" this is not true when the flux is empty, last() will fail, while takeLast will just return a new empty flux – xrobert35 Jun 02 '21 at 10:14