Flatmap的使用与匹配错误类型

使用flatmap从上行数据流发布者中获取数据并打平至一个数据流中,在本例中,将演示使用mapError将错误类型进行映射

步骤一:自定义错误类型

import Foundation
import UIKit
import Combine

enum RequestError: Error {
    case sessionError(error: Error)
}

步骤二:定义发布者和订阅者

//: we will send URLs through this publisher to trigger requests
let URLPublisher = PassthroughSubject<URL, RequestError>()

//: use `flatMap` to turn a URL into a requested data publisher
let subscription = URLPublisher.flatMap { requestURL in
    URLSession.shared
        .dataTaskPublisher(for: requestURL)
        .mapError { error -> RequestError in
            RequestError.sessionError(error: error)
    }
}
.assertNoFailure()
.sink { result in
    print("Request completed!")
    _ = UIImage(data: result.data)
}

步骤三:发射数据

URLPublisher.send(URL(string: "https://httpbin.org/image/jpeg")!)

Made with in Shangrao,China By 老雷

Copyright © devler.cn 1987 - Present

赣ICP备19009883号-1