即使在事件发布后,Combine 中的超时运算符也会超时

Jan*_*ani 2 ios swift combine

我在组合中使用超时运算符,我的理解是,仅当发布者不发布事件时才会超时,但即使发布了值,它似乎也会超时。

来自文档

如果指定的时间间隔过去而没有从上游发布者收到任何事件,则发布者终止。

import PlaygroundSupport
import Combine
import Foundation

PlaygroundPage.current.needsIndefiniteExecution = true

let subject = PassthroughSubject<String, Never>()
let cancellable = subject
    .timeout(.seconds(5), scheduler: DispatchQueue.main)
    .sink(
          receiveCompletion: { print ("completion: \($0) at \(Date())") },
          receiveValue: { print ("value: \($0) at \(Date())") }
     )

subject.send("Sending data")

/*
Prints
value: Sending data at 2021-01-06 22:41:12 +0000
completion: finished at 2021-01-06 22:41:17 +0000
*/
Run Code Online (Sandbox Code Playgroud)

难道是我对运营商的理解有误?

New*_*Dev 5

您误解了您引用的文字的含义。它表示,如果在指定的时间间隔内没有收到任何事件,则发布者将终止,这意味着在您的示例中,如果在前 5 秒内没有收到任何值。

文档还提供了一个略有不同的示例来说明这一点。

因此,换句话说,如果您将其添加到示例中:

DispatchQueue.main.async(deadline: .now() + 3) { subject.send("in 3 seconds") }
Run Code Online (Sandbox Code Playgroud)

那么你会得到以下输出:

DispatchQueue.main.async(deadline: .now() + 3) { subject.send("in 3 seconds") }
Run Code Online (Sandbox Code Playgroud)

最后一个值后 5 秒完成。