gpt4 book ai didi

swift - 为什么 subscribe(subject) 返回 AnyCancellable 但 subscribe(subscriber) Void?

转载 作者:行者123 更新时间:2023-11-30 10:29:34 27 4
gpt4 key购买 nike

我正在使用 Swift Joint,但不明白两者之间的区别

func subscribe<S>(_ subscriber: S) where S : Subscriber, Self.Failure == S.Failure, Self.Output == S.Input

func subscribe<S>(_ subject: S) -> AnyCancellable where S : Subject, Self.Failure == S.Failure, Self.Output == S.Output

为什么一个返回 AnyCancellable 而另一个返回 Void

我有一个自定义订阅者,所以我使用它完全安全

myPublisher.subscribe(myCustomSubscriber)

无需处理AnyCancellable

最佳答案

更新:

正如我下面的解释,您的自定义 Subscriber (我在下面的代码中将其命名为 MySubscriber )应该实现 Cancellable协议(protocol)。现在,您可以通过将订阅添加到 Set<AnyCancellable> 来管理订阅。 。当订阅者被取消时,订阅也会被取消。

<小时/>

我也有同样的担忧。我有一个自定义订阅者 Subscribers.MySubscriber并想添加功能Publisher.mySubscriber()就像Combine 对 Subscribers.Sink 所做的那样和Publisher.sink() 。但我不知道怎么办Publisher.sink()可以返回 AnyCancellable 。几分钟后,我猜测如何解决Publisher.sink()已实现:

extension Publisher {
public func mySink(receiveCompletion: @escaping ((Subscribers.Completion<Self.Failure>) -> Void), receiveValue: @escaping ((Self.Output) -> Void)) -> AnyCancellable {
let sink = Subscribers.Sink<Self.Output, Self.Failure>(receiveCompletion: receiveCompletion, receiveValue: receiveValue)
subscribe(sink)
return AnyCancellable(sink)
}
}

所以定制订阅者应该符合Cancellable ,并保留订阅引用,以便在订阅者的 cancel() 调用时取消订阅,如下所示:

final class MySubscriber<Input, Failure: Error>: Subscriber, Cancellable {

var subscription: Subscription?

// ...

init() {}

func receive(subscription: Subscription) {
// ...
self.subscription = subscription
}

func receive(_ input: Input) -> Subscribers.Demand {
// ...
return .unlimited
}

func receive(completion: Subscribers.Completion<Failure>) {
// ...
}

func cancel() {
subscription?.cancel()
subscription = nil
}
}

所以我的函数Publisher.mySubscriber()函数将是:

extension Publisher {
public func mySubscriber() -> AnyCancellable {
let mySubscriber = MySubscriber<Output, Failure>()
subscribe(mySubscriber)
return AnyCancellable(mySubscriber)
}
}

关于swift - 为什么 subscribe(subject) 返回 AnyCancellable 但 subscribe(subscriber) Void?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59424964/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com