我有一个多个按钮;当我按下新按钮时,之前(使用另一个按钮)运行请求应该被中断并且新运行。如何实现它?
for (button : Buttons) {
button.setOnClickListener(b -> networkApi.getLongContentFromUrl(url)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<JsonElement>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(JsonElement jsonElement) {
//do with result
}
}));
}
答案 0 :(得分:3)
您可以拥有一个公共SerialSubscription
,并在点击按钮时将您的订阅者分配给它。它将取消订阅,从而取消您之前的流:
SerialSubscription serial = new SerialSubscription();
for (Button btn : buttons) {
btn.setOnClickListener(e -> {
Subscriber<JsonElement> s = new Subscriber<JsonElement>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {}
@Override
public void onNext(JsonElement jsonElement) {
//do with result
}
};
serial.set(s);
networkApi.getLongContentFromUrl(url)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(s);
});
}