Search code examples
javakotlinreactive-programmingrx-java2rx-kotlin

Get N last objects emitted by observable in RxJava2


I have a Observables which emits some numbers and I simply want to take last N elements.

I have following code (I'm using RxKotlin which is simply a wrapper on RxJava):

val list = listOf(1,2,3,4,5,6,7,8,9,10)
Observable.fromIterable(list)
          .buffer(3, 1)
          .lastOrError()
          .subscribe{value -> println(value)}

Unfortunately the result is [10], as I looked closer what the buffer operator returns, I saw this:

[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
[9, 10]
[10] 

is there a way to get last "full" buffer -> [8, 9, 10] ?


Solution

  • In RxJava, many operators have the name that matches the common language expression of the same operation: take + last N -> takeLast(int n):

    Observable.range(1, 10)
       .takeLast(3)
       .toList() // <--  in case you want it as a list
       .subscribe(System.out::println);