RxJava-如何背压平面图()

RxJava- How to backpressure a flatmap()

也许我忽略了运算符的简单组合(或者 RxJava 的固有取消行为)。但是假设我有一个热观察 selectedItem 平面映射到 RxJava-JDBC 查询。

@Test
public void testFlatMapBackPressure() { 
    Database db = null; //assign db

    BehaviorSubject<Integer> selectedItem = BehaviorSubject.create();

    //can I backpressure the queries so only the latest one is running, and any previous is cancelled?
    Observable<List<Integer>> currentValues = selectedItem.flatMap(i ->  db.select("SELECT VALUE FROM MY_TABLE WHERE ID =?")
            .parameter(i)
            .getAs(Integer.class)
            .toList());
}

我如何反压 flatMap() 运算符,使其始终只执行最新的查询(并取消之前的任何查询)。我有点想要一个背压的 flatMap 运算符来做这样的事情,其中​​ "X" 表示取消先前的查询

有没有办法做到这一点?还是已经完成了,只是我没有看到?

听起来您需要 switchMap() 而不是 flatMap()

Returns a new Observable by applying a function that you supply to each item emitted by the source Observable that returns an Observable, and then emitting the items emitted by the most recently emitted of these Observables.