[转] Combine学习笔记 - Subscription

参考链接: https://github.com/AvdLee/CombineSwiftPlayground

3个月前 130次点击 来自 移动端

标签: Swift

Subscription details

  • A subscriber will receive a single subscription
  • Zero or more values can be published
  • At most one {completion, error} will be called
  • After completion, nothing more is received

以下示例主要演示了订阅过程中回调事件的处理,使用一个不太恰当的说法,演示的是订阅的生命周期

import Combine

enum ExampleError: Swift.Error {
    case somethingWentWrong
}

let subject = PassthroughSubject<String, ExampleError>()

// The handleEvents operator lets you intercept
// All stages of a subscription lifecycle
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)")
    }

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 Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1