智慧屏安装APP的最佳实践与跨平台小程序开发的结合
748
2022-11-03
Future - 基于微框架设计思想的异步执行及结果响应类
Future
Swift µframework providing Future
This library is inspired by the talk of Javier Soto at SwiftSubmit2015 and the Future implementation in Scala.
And this is using antitypical/Result.
Why we need Future?
Traditional async code
func requestRepository(repoId: Int64, completion: (Repository?, NSError?) -> Void) {} func requestUser(userId: Int64, completion: (User?, NSError?) -> Void) {} // get owner info of a given repository requestRepository(12345) { repo, error in if let repo = repo { requestUser(repo.ownerId) { user, error in if let user = user { // do something } else { // error handling } } } else { // error handling } }
Code with Future
let future = requestRepository(12345) .map { $0.ownerId } .flatMap(requestUser)future.onCompleted { result in switch result { case .Success(let user): println(user) case .Failure(let error): println(error) }}
Shorthand by using operator
let future = requestRepository(12345) <^> { $0.ownerId } >>- requestUserfuture.onCompleted { result in switch result { case .Success(let user): println(user) case .Failure(let error): println(error) }}
Usage
map <^>
let f = requestUser("nghialv") <^> { $0.id }f.onSuccess { userId in println(userId)}
flatMap >>-
let f = searchRepositories("Hakuba") <^> { $0.first!.ownerName } >>- requestUserf.onComplete { result in switch result { case .Success(let user): println(user) case .Failure(let error): println(error) }}
filter
let e = NSError(domain: "noSuchElement", code: 1, userInfo: nil)let f1 = searchRepositories("Hakuba")let f = f1.filter(e){ $0.count > 0 } <^> { $0.first!.ownerName } >>- requestUserf.onComplete { result in switch result { case .Success(let user): println(user) case .Failure(let error): println(error) }}
andThen
// side-effectvar reposCount = 0 let f1 = searchRepositories("Hakuba")let f2 = f1.andThen { result in switch result { case .Success(let repos): reposCount = repos.value.count case .Failure(let error): break }}let f3 = f2 <^> { $0.first!.ownerName } >>- requestUser f3.onComplete { result in switch result { case .Success(let user): println(user) case .Failure(let error): println(error) }}
recover zip
let f1 = searchRepositories("Future")let f2 = requestUser("nghialv") let f3 = f1.zip(f2)f3.onSuccess { repos, user in println(repos) println(user)}
flatten
Installation
Using Carthage
Insert github "nghialv/Future" to your CartfileRun carthage update
Using Cocoapods
Insert use_frameworks! to your PodfileInsert pod "Future" to your PodfileRun pod install
Using Submodule
Requirements
Swift 1.2 (Xcode 6.3 or later)iOS 8.0 or later
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~