RxJava-缓存可观察更新并发出最大值
我当前有一个RxJava-缓存可观察更新并发出最大值,java,caching,java-8,stream,rx-java,Java,Caching,Java 8,Stream,Rx Java,我当前有一个可观察的发出一个表示产品ID更新的对象。该更新可以是新的添加的ID,也可以是过期的,需要删除 public class ProductIDUpdate { enum UpdateType { ADDITION, DELETEION; } private int id; private UpdateType type; public ProductIDUpdate(int id) { this(id, Upd
可观察的
发出一个表示产品ID更新的对象。该更新可以是新的添加的ID
,也可以是过期的,需要删除
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;
}
}
我想用最大的ID值跟踪更新,因此我想修改流,以便发出当前最高的ID。如何在流中缓存更新项,以便在删除当前最高ID的情况下,发出下一个最高可用ID?我对Rx一无所知,但我的理解是:
- 你有一堆产品ID。我不清楚您是否在发送给您的类的某些消息中接收到它们,或者您是否从一开始就知道所有ID
- 您希望在产品id源的顶部创建一个流,该流在任何时间点发出最高的可用id
如果我的理解是正确的,那么使用?您可以使用反向比较器将ID缓存在队列中(默认情况下,它将最小的元素保留在堆的顶部),当您想要发出一个新值时,只需弹出顶部值。类似的东西可以满足您的要求吗
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();
}
如果删除过滤器()
,将打印:
ProductIDUpdate{id=1, type=ADDITION}
ProductIDUpdate{id=4, type=ADDITION}
ProductIDUpdate{id=5, type=ADDITION}
ProductIDUpdate{id=6, type=ADDITION}
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}
哪个流,哪个缓存?这些部分对我来说不够清楚。没有缓存,流是我正在接收的更新的可见部分。我不确定如何处理数据以仅发出我所需的值-我假设预期行为需要缓存。那么,您将如何调用流?它实际上是一个Java
流
,还是你可以观察到的对象?很抱歉,仍然试图解决这个问题。好的,很抱歉,流是一个RxJava可观察流-也就是说,它发出ProductIdUpdate对象,我正在从流源接收这些对象。