I created a request to the youtube api search. When a request is sent, requests before it must be canceled and no updates are made to the cache.
I used a CompositeDisposable to add each Disposable and clear it when creating a new request.
However, as I noticed that the previous request was not canceled, the cache was still updated.
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);
}
});
}