用 Swift 5 编写
RxAlamoRecord 结合了 AlamoRecord 和 RxSwift 库的功能,创建了一个便于反应式访问 API 的网络层。
要求
- iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
- Xcode 10.2+
- Swift 5.1
安装
RxAlamoRecord 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile 中:
pod 'RxAlamoRecord'
入门
RxAlamoRecord 无法在不了解 AlamoRecord 和 RxSwift 基本原理的情况下使用。在继续之前,建议您先了解这两个库的工作方式。
目的
RxAlamoRecord 允许您将 API 响应直接绑定到 AlamoRecordRelay
和 Action
对象。Action 是由 RxSwiftCommunity 创建的一个强大的扩展库。
AlamoRecordRelay
该对象的行为与 BehaviorRelay 完全相同,但 AlamoRecordRelay
可以发出错误。当通过 RxAlamoRecord 绑定时,必须使用 AlamoRecordRelay
的一个实例;否则,如果 API 请求返回错误或失败,应用程序将会崩溃。
为了简化示例,假设每个示例中都包含这些变量
let posts = AlamoRecordRelay<[Post]>(value: [])
let post = AlamoRecordRelay<Post?>(value: nil)
lazy var failureAction: Action<ApplicationError, Swift.Never> = {
return Action { [weak self] error in
// Do something with the error
return Observable.empty()
}
}()
Post
实例
获取所有 GET
https://jsonplaceholder.typicode.com/posts
Post.rx
.all()
.execute()
.bind(to: posts, failure: failureAction)
.disposed(by: disposeBag)
Post
实例
创建 POST
https://jsonplaceholder.typicode.com/posts
Post.rx
.create()
.withParameters(["userId": userId, "title": title, "body": body])
.execute()
.bind(to: post, failure: failureAction)
.disposed(by: disposeBag)
查找《Post》实例
GET
https://jsonplaceholder.typicode.com/posts/1
Post.rx
.find(id: 1)
.execute()
.bind(to: post, failure: failureAction)
.disposed(by: disposeBag)
更新《Post》实例
PUT
https://jsonplaceholder.typicode.com/posts/1
post.value?
.rx
.update()
.withParameters(["userId": userId, "title": title, "body": body])
.execute()
.bind(to: post, failure: failureAction)
.disposed(by: disposeBag)
这也可以在类级别上完成
Post.rx
.update(id: 1)
.withParameters(["userId": userId, "title": title, "body": body])
.execute()
.bind(to: post, failure: failureAction)
.disposed(by: disposeBag)
销毁《Post》实例
DELETE
https://jsonplaceholder.typicode.com/posts/1
lazy var destroyedAction: Action<Void, Swift.Never> = {
return Action { [weak self] in
// The post is now destroyed
return Observable.empty()
}
}()
post.value?
.rx
.destroy()
.execute()
.bind(to: destroyedAction, failure: failureAction)
.disposed(by: disposeBag)
这也可以在类级别上完成
Post.rx
.destroy(id: 1)
.execute()
.bind(to: destroyedAction, failure: failureAction)
.disposed(by: disposeBag)
在失败时分配默认值
如果API请求失败,也可以将默认值分配给AlamoRecordRelay/Action对象
let postTitle = AlamoRecordRelay<String?>(value: nil)
Post.rx
.find(id: 1)
.execute()
.map { $0.title }
.bind(to: postTitle, valueOnFailure: "Default Title")
.disposed(by: disposeBag)
lazy var postTitleAction: Action<String, Swift.Never> = {
return Action { [weak self] title in
// Do something with the title
return Observable.empty()
}
}()
Post.rx
.find(id: 1)
.execute()
.map { $0.title }
.bind(to: postTitleAction, valueOnFailure: "Default Title")
.disposed(by: disposeBag)
下载示例项目,看看使用RxAlamoRecord创建具有反应式网络层的应用程序有多容易!
作者
Dalton Hinterscher, [email protected]
致谢
在页眉图片中使用的Responsive Logo由ReactiveX团队设计
许可证
RxAlamoRecord遵从MIT许可证。更多信息请参阅LICENSE文件。