[英]RxJava - Cache Observable Updates and Emit Largest Values
I currently have an Observable<ProductIDUpdate>
emitting an object that represents an update of a product ID. 我目前有一个Observable<ProductIDUpdate>
发出一个对象,该对象表示产品ID的更新。 The update can either be the ID is an new ADDITION
or has expired and requires DELETION
. 该更新可以是ID为新的ADDITION
,也可以是过期的,并且需要DELETION
。
public class ProductIDUpdate {
enum UpdateType {
ADDITION, DELETEION;
}
private int id;
private UpdateType type;
public ProductIDUpdate(int id) {
this(id, UpdateType.ADDITION);
}
public ProductIDUpdate(int id, UpdateType type) {
this.id = id;
this.type = type;
}
}
I want to track the update with the largest ID value, hence I want to modify the stream so that the current highest ID is emitted. 我想跟踪具有最大ID值的更新,因此我想修改流,以便发出当前最高ID。 How would I cache the update items in the stream such that if the current highest ID is deleted, the next highest available ID is emitted? 我将如何在流中缓存更新项,以便如果删除当前最高ID,则发出下一个最高可用ID?
I don't know anything about Rx, but here's my understanding: 我对Rx一无所知,但这是我的理解:
If my understanding is correct, how about using a PriorityQueue ? 如果我的理解是正确的,那么如何使用PriorityQueue呢? You cache ids in the queue with a reverse comparator (it keeps the smallest element at the top of the heap by default) and when you want to emit a new value you just pop the top value. 您可以使用反向比较器将ID缓存在队列中(默认情况下,它将最小的元素保留在堆的顶部),当您要发出新值时,只需弹出顶部值即可。
Can something like that meet your requirements? 可以满足您的要求吗?
public static void main(String[] args) {
Observable<ProductIDUpdate> products =
Observable.just(new ProductIDUpdate(1, ADDITION),
new ProductIDUpdate(4, ADDITION),
new ProductIDUpdate(2, ADDITION),
new ProductIDUpdate(5, ADDITION),
new ProductIDUpdate(1, DELETION),
new ProductIDUpdate(5, DELETION),
new ProductIDUpdate(3, ADDITION),
new ProductIDUpdate(6, ADDITION));
products.distinctUntilChanged((prev, current) -> prev.getId() > current.getId())
.filter(p -> p.getType().equals(ADDITION))
.subscribe(System.out::println,
Throwable::printStackTrace);
Observable.timer(1, MINUTES) // just for blocking the main thread
.toBlocking()
.subscribe();
}
This prints: 打印:
ProductIDUpdate{id=1, type=ADDITION}
ProductIDUpdate{id=4, type=ADDITION}
ProductIDUpdate{id=5, type=ADDITION}
ProductIDUpdate{id=6, type=ADDITION}
If you remove the filter()
, this prints: 如果删除filter()
,则打印:
ProductIDUpdate{id=1, type=ADDITION}
ProductIDUpdate{id=4, type=ADDITION}
ProductIDUpdate{id=5, type=ADDITION}
ProductIDUpdate{id=5, type=DELETION}
ProductIDUpdate{id=6, type=ADDITION}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.