Debug发布者调试

本小节演示如何使用handleEventsprint(_:),breakpoint(_:)调试发布者的数据是否正确发布,特别是在自定义Publisher的时候,调试的过程非常有必要

import Foundation
import UIKit
import Combine

enum ExampleError: Swift.Error {
    case somethingWentWrong
}

let subject = PassthroughSubject<String, ExampleError>()
let subscription = subject
    .handleEvents(receiveSubscription: { (subscription) in
        print("Receive subscription")
    }, receiveOutput: { output in
        print("Received output: \(output)")
    }, receiveCompletion: { _ in
        print("Receive completion")
    }, receiveCancel: {
        print("Receive cancel")
    }, receiveRequest: { demand in
        print("Receive request: \(demand)")
    }).replaceError(with: "Error occurred").sink { _ in }

subject.send("Hello!")
subscription.cancel()

// Prints out:
// Receive request: unlimited
// Receive subscription
// Received output: Hello!
// Receive cancel

//subject.send(completion: .finished)

/*:
### `print(_:)`
Prints log messages for every event
*/

let printSubscription = subject
    .print("Print example")
    .replaceError(with: "Error occurred")
    .sink { _ in }

subject.send("Hello!")
printSubscription.cancel()

// Prints out:
// Print example: receive subscription: (PassthroughSubject)
// Print example: request unlimited
// Print example: receive value: (Hello!)
// Print example: receive cancel

/*:
### `breakpoint(_:)`
Conditionally break in the debugger when specific values pass through
*/
let breakSubscription = subject
    .breakpoint(receiveOutput: { value in
      value == "Hello!"
    })

Made with in Shangrao,China By 老雷

Copyright © devler.cn 1987 - Present

赣ICP备19009883号-1