Future与Promises

Future是一个发布者,它让您可以在任何异步调用中组合,并使用该调用生成值或作为发布者完成调用。
当您想要发出单个请求或获得单个响应时,它非常适合具有完成处理程序闭包的API。

比较类似的概念还有Promise异步编程,简单的说,Future适合异步编程下回调的处理。

步骤一: 定义数据类型与错误类型

import Foundation
import Combine

enum FetchError: Error {
    case userNotFound
}

struct User {
    let id: Int
    let name: String
}

let users = [User(id: 0, name: "Antoine"), User(id: 1, name: "Henk"), User(id: 2, name: "Bart")]

步骤二:用于查询用户数据的回调函数

func fetchUser(for userId: Int, completion: (_ result: Result<User, FetchError>) -> Void) {
    if let user = users.first(where: { $0.id == userId }) {
        completion(Result.success(user))
    } else {
        completion(Result.failure(FetchError.userNotFound))
    }
}

步骤三:发布订阅

let fetchUserPublisher = PassthroughSubject<Int, FetchError>()

fetchUserPublisher
    .flatMap { userId -> Future<User, FetchError> in
        Future { promise in
            fetchUser(for: userId) { (result) in
                switch result {
                case .success(let user):
                    promise(.success(user))
                case .failure(let error):
                    promise(.failure(error))
                }
            }
        }
}
.map { user in user.name }
.catch { (error) -> Just<String> in
    print("Error occurred: \(error)")
    return Just("Not found")
}
.sink { result in
    print("User is \(result)")
}

fetchUserPublisher.send(0)
fetchUserPublisher.send(5)

输出:

User is Antoine
Error occurred: userNotFound
User is Not found

Made with in Shangrao,China By 老雷

Copyright © devler.cn 1987 - Present

赣ICP备19009883号-1