[英]RxJava - Cache Observable Updates and Emit Largest Values
我目前有一个Observable<ProductIDUpdate>
发出一个对象,该对象表示产品ID的更新。 该更新可以是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;
}
}
我想跟踪具有最大ID值的更新,因此我想修改流,以便发出当前最高ID。 我将如何在流中缓存更新项,以便如果删除当前最高ID,则发出下一个最高可用ID?
我对Rx一无所知,但这是我的理解:
如果我的理解是正确的,那么如何使用PriorityQueue呢? 您可以使用反向比较器将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}
如果删除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.