3

How do to use operators so that i always get the previous and the current value? If possible i want to avoid creating state outside the pipe.

- time ->
1      2      3      4
|      |      |      |
Operations
       |      |      |
       (1,2)  (2,3)  (3,4)

Note that every value besides the first and the last one have to appear twice, so a simple buffer won't do.

I thought about combining skip with merge and buffer but merge does not seem to guarantee ordering.

val s = PublishSubject.create<Int>()
s.mergeWith(s.skip(1)).buffer(2).subscribe{i -> print(i)}
s.onNext(1)
s.onNext(2)
s.onNext(3)
s.onNext(4)


output:
[1, 2][2, 3][3, 4]

val o = Observable.just(1,2,3,4)
o.mergeWith(o.skip(1)).buffer(2).subscribe{i -> print(i)}

output:
[1, 2][3, 4][2, 3][4]

(the sole 4 is fine, and expected)

felix-ht
  • 1,697
  • 15
  • 16
  • 2
    Have you tried `buffer(2, 1)`? Also, you can use `scan`. If you are a bit familiar with C# checkout [this](http://www.zerobugbuild.com/?p=213) – momvart May 26 '20 at 14:03

1 Answers1

6

Looks like you still can use buffer:

Observable.just(1, 2, 3, 4)
    .buffer(2, 1)
    .subscribe { println(it) }

// prints
// [1, 2]
// [2, 3]
// [3, 4]
// [4]
Andrei Tanana
  • 7,932
  • 1
  • 27
  • 36
  • 2
    Skip feels like a horrible naming in this context. I was assuming that the skip value within buffer would do the same thing as the skip operator. In Scala this parameter is called step, which is certainly much more intuitive. (Or the even better stride in the ml domain) – felix-ht Jun 02 '20 at 14:07