简体   繁体   English

Android Retrofit POST请求缓存

[英]Android Retrofit POST request cache

Which is best way to store retrofit POST request cache ? 哪个是存储改造 POST请求缓存的最佳方法?

I will store response and using that response while user is offline. 我会在用户离线时存储响应并使用该响应。 I was referred this link. 我被推荐这个链接。
1) Can Retrofit with OKHttp use cache data when offline 1) 使用OKHttp进行改造可以在离线时使用缓存数据
2) Cache POST requests with OkHttp 2) 使用OkHttp缓存POST请求

But in this link cache mechanism work only GET method. 但在此链接缓存机制中只能使用GET方法。
- It is possible to store cache in post request using retrofit ? - 可以使用改造在post请求中存储缓存吗?
- Is any library to handle network cache? - 是否有任何库来处理网络缓存?

Thanks 谢谢

OkHttp支持文件缓存

This is the solution we ended up with 这是我们最终解决的问题

public class OnErrorRetryCache<T> {

    public static <T> Observable<T> from(Observable<T> source) {
         return new OnErrorRetryCache<>(source).deferred;
    }

    private final Observable<T> deferred;
    private final Semaphore singlePermit = new Semaphore(1);

    private Observable<T> cache = null;
    private Observable<T> inProgress = null;

    private OnErrorRetryCache(Observable<T> source) {
        deferred = Observable.defer(() -> createWhenObserverSubscribes(source));
    }

    private Observable<T> createWhenObserverSubscribes(Observable<T> source) 
    {
        singlePermit.acquireUninterruptibly();

        Observable<T> cached = cache;
        if (cached != null) {
            singlePermit.release();
            return cached;
        }

        inProgress = source
                .doOnCompleted(this::onSuccess)
                .doOnTerminate(this::onTermination)
                .replay()
                .autoConnect();

        return inProgress;
    }

    private void onSuccess() {
        cache = inProgress;
    }

    private void onTermination() {
        inProgress = null;
        singlePermit.release();
    }
}

We needed to cache the result of an HTTP request from Retrofit. 我们需要从Retrofit缓存HTTP请求的结果。 So this was created, with an observable that emits a single item in mind. 所以这是创建的,其中一个可观察的内容会记住一个项目。

If an observer subscribed while the HTTP request was being executed, we wanted it to wait and not execute the request twice, unless the in-progress one failed. 如果观察者在执行HTTP请求时订阅,我们希望它等待并且不执行请求两次,除非正在进行的请求失败。 To do that the semaphore allows single access to the block that creates or returns the cached observable, and if a new observable is created, we wait until that one terminates. 为此,信号量允许单个访问创建或返回高速缓存的observable的块,如果创建了新的observable,我们将等待,直到该终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM