RxJava-缓存可观察的更新并发出最大的值

时间:2018-09-09 18:29:55

标签: java caching java-8 stream rx-java

我目前有一个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?

2 个答案:

答案 0 :(得分:0)

我对Rx一无所知,但这是我的理解:

  • 您有很多产品ID。对于我来说,目前还不清楚您是否随着时间的流逝而收到它们,作为发送给班级的某些消息的一部分,还是从一开始就知道所有ID
  • 您想在产品ID来源的顶部创建一个流,该流在任何时间点都发出最高的可用ID。

如果我的理解正确,那么如何使用PriorityQueue?您可以使用反向比较器将ID缓存在队列中(默认情况下,它会将最小的元素保留在堆的顶部),并且当您要发出新值时,只需弹出顶部值即可。

答案 1 :(得分:0)

类似的东西可以满足您的要求吗?

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}
相关问题