如何取消 Retrofit2 Rxjava2



我创建了一个对youtube api搜索的请求。 发送请求时,必须取消之前的请求,并且不会对缓存进行任何更新。

我使用复合一次性添加每个一次性并在创建新请求时清除它。

但是,由于我注意到以前的请求没有被取消,因此缓存仍然被更新。

disposable.clear();
disposable.add(Network.search(nextPageToken, (isSearchingOnline() ? mFilterText : ""), item.topicId, listener));

public static Disposable search(String nextPageToken, String query, String topicId, String publishedAfter, OnYoutubeSearchListener listener) {
YParams yParam = new YParams(50, Constants.YOUTUBE_DEVERLOPE_KEY, "snippet", "video", nextPageToken, "10", query, publishedAfter, topicId);
if (cacheData.containsKey(yParam)) {
if (listener != null) {
for (Map.Entry<YParams, List<VideoBean>> entry : cacheData.entrySet()) {
YParams key = entry.getKey();
List<VideoBean> value = entry.getValue();
if (key.equals(yParam)) {
listener.onReturnPageToken(key.getNextPageToken());
listener.onSuccess(value);
break;
}
}
}
return new CompositeDisposable();
}
return Network.getYoutubeApi().search(50, Constants.YOUTUBE_DEVERLOPE_KEY, "snippet", "video", nextPageToken, "10", "", publishedAfter, "")
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.flatMap((Function<Videos, ObservableSource<Videos>>) videos -> {
if (videos.items.size() > 0) {
StringBuilder builder = new StringBuilder();
for (Videos.Item i : videos.items) {
builder.append(i.id.videoId);
builder.append(",");
}
yParam.setNextPageToken(videos.nextPageToken);
if (listener != null) {
listener.onReturnPageToken(videos.nextPageToken);
}
return Network.getYoutubeApi().getVideosDetail(Constants.YOUTUBE_DEVERLOPE_KEY, builder.substring(0, builder.length() - 1), "snippet,contentDetails,statistics");
}
return Observable.fromArray(Videos.EMPTY_VIDEOS);
})
.observeOn(AndroidSchedulers.mainThread())
.map(new Function<Videos, List<VideoBean>>() {
@Override
public List<VideoBean> apply(Videos videos) {
List<VideoBean> list = new ArrayList();
for (Videos.Item bean : videos.items) {
list.add(new VideoBean(bean.id.videoId, bean.snippet.title, bean.snippet.description, bean.snippet.thumbnails._default.url, bean.snippet.channelTitle, bean.contentDetails.duration, bean.snippet.publishedAt, 0));
}
return list;
}
})
.subscribe(items -> {
if (items != null && items.size() > 0) {
cacheData.put(yParam, items);
}
if (listener != null) {
listener.onSuccess(items);
}
}, throwable -> {
if (listener != null) {
listener.onFailed(throwable);
}
});
}

如何在安卓中取消 Retrofit2 Rxjava2?

您必须保留对Disposable对象的引用并对其调用dispose()

相关内容

  • 没有找到相关文章

最新更新