ReactiveCocoa AFNetworking PINCache 网络数据缓存

最近需要实现对网络数据的缓存,通过综合考虑最后决定采用PINCache作为底层缓存框架,PINCache是Pinterest的程序员在Tumblr的TMCache基础上发展而来的,经过Pinterest的实战考验,无疑是一套优秀的开源缓存框架。

流程图如下:

ReactiveCocoa AFNetworking PINCache 网络数据缓存_第1张图片
缓存.jpg

分析:

*进入页面同时检查是否有缓存和请求网络数据
*如果有缓存,读取缓存,读取缓存的时间大于接口的请求数据的时间就停止读取缓存,反之则刷新UI
*网络数据请求成功的就刷新UI,同时异步缓存

主要代码:

NSString *cacheKey = [TTAPIParamsGenerator cacheKeyGenerator:params methodName:methodName];

RACSignal *cacheSignal = [[[TTOldService cacheManager] cacheObjectForKey:cacheKey] catchTo:[RACSignal empty]];
RACSignal *remoteSignal = [[self rac_PostWithParams:params methodName:methodName] flattenMap:^RACStream *(id value) {
    if (value) {
        [[TTOldService cacheManager]  setObject:value forKey:cacheKey block:^(PINCache * _Nonnull cache, NSString * _Nonnull key, id  _Nullable object) {
            
        }];
    }
    return [RACSignal return:value];
}];

return [RACSignal merge:@[[cacheSignal takeUntil:remoteSignal], remoteSignal]];

Demo链接

相关缓存文章:
LRU cache实现 (Java)
缓存算法(页面置换算法)-FIFO、LFU、LRU

你可能感兴趣的:(ReactiveCocoa AFNetworking PINCache 网络数据缓存)