当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift Result.Publisher delay(for:tolerance:scheduler:options:)用法及代码示例


实例方法

delay(for:tolerance:scheduler:options:)

在特定调度程序上将所有输出延迟到下游接收器的指定时间量。

声明

func delay<S>(
    for interval: S.SchedulerTimeType.Stride,
    tolerance: S.SchedulerTimeType.Stride? = nil,
    scheduler: S,
    options: S.SchedulerOptions? = nil
) -> Publishers.Delay<Self, S> where S : Scheduler

返回值

延迟向下游接收者传递元素和完成的发布者。

参数

interval

延迟的时间量。

tolerance

传递延迟事件的允许容差。 Delay 发布者可能会早于或晚于指定的时间间隔交付元素。

scheduler

传递延迟事件的调度程序。

options

与调度程序行为相关的选项。

详述

当您需要将元素交付到下游延迟指定的时间时,请使用 Publisher/delay(for:tolerance:scheduler:options:)

在此示例中, Timer 每秒发布一个事件。 Publisher/delay(for:tolerance:scheduler:options:) 运算符将初始元素的传递保持 3 秒(±0.5 秒),之后每个元素在指定的延迟后传递到主运行循环的下游:


let df = DateFormatter()
df.dateStyle = .none
df.timeStyle = .long
cancellable = Timer.publish(every: 1.0, on: .main, in: .default)
    .autoconnect()
    .handleEvents(receiveOutput: { date in
        print ("Sending Timestamp \'\(df.string(from: date))\' to delay()")
    })
    .delay(for: .seconds(3), scheduler: RunLoop.main, options: .none)
    .sink(
        receiveCompletion: { print ("completion: \($0)", terminator: "\n") },
        receiveValue: { value in
            let now = Date()
            print ("At \(df.string(from: now)) received  Timestamp \'\(df.string(from: value))\' sent: \(String(format: "%.2f", now.timeIntervalSince(value))) secs ago", terminator: "\n")
        }
    )


// Prints:
//    Sending Timestamp '5:02:33 PM PDT' to delay()
//    Sending Timestamp '5:02:34 PM PDT' to delay()
//    Sending Timestamp '5:02:35 PM PDT' to delay()
//    Sending Timestamp '5:02:36 PM PDT' to delay()
//    At 5:02:36 PM PDT received  Timestamp '5:02:33 PM PDT' sent: 3.00 secs ago
//    Sending Timestamp '5:02:37 PM PDT' to delay()
//    At 5:02:37 PM PDT received  Timestamp '5:02:34 PM PDT' sent: 3.00 secs ago
//    Sending Timestamp '5:02:38 PM PDT' to delay()
//    At 5:02:38 PM PDT received  Timestamp '5:02:35 PM PDT' sent: 3.00 secs ago

延迟影响元素的交付和完成,但不影响原始订阅。

可用版本

iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Result.Publisher delay(for:tolerance:scheduler:options:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。