RxObservableCache 3.0.0

RxObservableCache 3.0.0

Alexey NenastevNikolay 维护。



  • 作者
  • Alexey Nenast'ev

Swift 5.0 | RU_Readme

RxObservableCache

允许您为 Observable 缓存数据

Cocoapods

pod 'RxObservableCache', '~> 2.0.0'

如何使用

1. 创建对象 CacheAssociation<T>

该对象用于访问缓存,T 是为缓存创建的数据类型。通过 CacheAssociation,与缓存建立连接,并设置对缓存进行读写操作的规则。

CacheAssociation.init(cacheIdentifier: CacheIdentifier, rule: CacheRule, groupId: CacheGroupId? = nil)
  • CacheIdentifier - 缓存数据的唯一标识符
  • CacheRule - 缓存交互规则
public enum CacheRule {
    case readOnly(ExpiredAfterSeconds) 
    case readWrite(ExpiredAfterSeconds) 
    case writeOnly
}
// ExpiredAfterSeconds - read the data from the cache only if they live there for no longer than the specified number of seconds

创建此类对象的最佳实践是在 CacheAssociation 类型上声明一个扩展,并将约束应用于 T

示例

extension CacheAssociation where T == News { 
    static func news(with id: Int, rule: CacheRule) -> CacheAssociation<News> {
        return .init(cacheIdentifier: "\(id)", rule: rule, groupId: nil)
    } 
}

2. 在 Observable/Single 上设置 CacheAssociation<T>

// somewhere in code 
func loadNews(by id: Int) -> Single<News> { ... }

loadNews(by: id)
  .associate(with: .news(with: id, .readWrite(30))
  .subscribe(onComplete: { ... })
  .disposed(by: bag)

// The handler will first look up the data in the cache by id and if they are there for no longer than 30 seconds, it will return them
// otherwise execute the original `loadNews (by: id)` after it is successful
// data will be written (cacheRule = .readWrite) to the cache.

CacheContainer

用于管理缓存,请使用单例CacheContainer,允许您清除所有缓存、禁用整体缓存或开启日志记录。当前实例可通过CacheContainer.instanceLazyInit访问。

CacheGroupId 缓存组

可以将缓存组合成组。对于组,您可以指定一组选项。

通过选项,您可以将组中缓存的数目进行限制。

CacheContainer.instanceLazyInit.set(options: [.maxGroupCaches(5)], for: "news") 

// When creating CacheAssociation, you need to specify a group
extension CacheAssociation where T == News {
     static func news (with id: Int, rule: CacheRule) -> CacheAssociation <News> {
         return .init (cacheIdentifier: "\ (id)", rule: rule, groupId: "news") // specify the group
     }
}

func loadNewsData(for id: Int) {
  loadNews(by: id)
    .associate(with: .news(with: id, .readWrite(30))
    .subscribe(onComplete: { ... })
    .disposed(by: bag)
}
 
loadNewsData(for: 101) 
loadNewsData(for: 102) 
loadNewsData(for: 103) 
loadNewsData(for: 104) 
loadNewsData(for: 105) 
loadNewsData(for: 106)
// There will be 5 caches in memory. If we assume that the requests were executed in order after
// run the last cache for 101 retire