简体   繁体   English

Rxjava - 如何获取当前和上一个项目?

[英]Rxjava - How to get the current and the previous item?

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.如果可能的话,我想避免在 pipe 之外创建 state。

- 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.我考虑过将skipmergebuffer结合起来,但合并似乎不能保证排序。

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: output:
[1, 2][2, 3][3, 4] [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: output:
[1, 2][3, 4][2, 3][4] [1, 2][3, 4][2, 3][4]

(the sole 4 is fine, and expected) (唯一的 4 很好,并且可以预期)

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让 map 等到当前索引项处理完毕,然后使用 RxJava 取出下一项进行处理? - How to make the map wait till the current index item is finished processing and then take the next item for processing using RxJava? 如何从列表中获取Arraylist中的Json响应 <Item> 使用RxJava和Kotlin - How to get Json Response in Arraylist from List<Item> using RxJava and Kotlin RxJava2:遍历项目并获取符合条件的项目 - RxJava2: Iterate over items and get the item matching a condition 获取流集合中的当前值和上一个值 - Get current and previous value in flow's collect RxJava - 如何在发出新项目时停止正在运行的任务 - RxJava - How to stop a running task when new item emitted RxJava2和改造:如何获取数据页面 - RxJava2 & Retrofit: How to get pages of data RxJava:如何转换单个<Response>单身<List<Item> &gt; - RxJava: How to transform a Single<Response> to Single<List<Item>> RxJava Kotlin如何从单个可观察对象中获取分离的对象<String> - RxJava Kotlin how to get separated objects from single observable<String> RxJava - Observable的zip列表if throw异常如何获得成功响应 - RxJava - zip list of Observable if throw exception how to get success response 当知道上一个和下一个潮汐时获取当前潮汐高度 - Get current tide height when previous and next tides are known
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM