如何订阅

本小节,我们将试着使用PassthroughSubject完成一个发布订阅过程

步骤一: 自定义一个错误类型

enum ExampleError: Swift.Error {
    case somethingWentWrong
}

步骤二: 使用PassthroughSubject作为发布者,PassthroughSubject包含两个参数,第一个是发布的数据类型,第二个是错误类型

let subject = PassthroughSubject<String, ExampleError>()

subject.handleEvents(receiveSubscription: { (subscription) in
        print("New subscription!")
    }, receiveOutput: { _ in
        print("Received new value!")
    }, receiveCompletion: { _ in
        print("A subscription completed")
    }, receiveCancel: {
        print("A subscription cancelled")
    })
    .replaceError(with: "Failure")
    .sink { (value) in
        print("Subscriber received value: \(value)")
    }

步骤三:使用send函数发送数据

send常用函数

  • send(input:String)函数向该subject添加新值

  • send(completion:.finished)发送完成

  • send(completion: someError)发送error

subject.send("Hello!")
subject.send("Hello again!")
subject.send("Hello for the last time!")
subject.send(completion: .failure(.somethingWentWrong))
subject.send("Hello?? :(")

输出:

New subscription!
Received new value!
Subscriber received value: Hello!
Received new value!
Subscriber received value: Hello again!
Received new value!
Subscriber received value: Hello for the last time!
A subscription completed
Subscriber received value: Failure

Made with in Shangrao,China By 老雷

Copyright © devler.cn 1987 - Present

赣ICP备19009883号-1