[英]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.