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


Swift Optional.Publisher debounce(for:scheduler:options:)用法及代码示例


实例方法

debounce(for:scheduler:options:)

仅在事件之间经过指定的时间间隔后发布元素。

声明

func debounce<S>(
    for dueTime: S.SchedulerTimeType.Stride,
    scheduler: S,
    options: S.SchedulerOptions? = nil
) -> Publishers.Debounce<Self, S> where S : Scheduler

返回值

仅在经过指定时间后才发布事件的发布者。

参数

dueTime

发布者在发布元素之前应该等待的时间。

scheduler

此发布者交付元素的调度程序

options

自定义此发布者的元素交付的调度程序选项。

详述

使用 Publisher/debounce(for:scheduler:options:) 运算符来控制值的数量和从上游发布者传递值之间的时间。此运算符对于处理突发或high-volume 事件流很有用,您需要将传递到下游的值的数量减少到您指定的速率。

在此示例中,PassthroughSubjectbounces 数组定义的计划发布元素。该数组由表示由 PassthroughSubject 发送的值的元组和一个 TimeInterval 组成,范围从 one-quarter 秒到 2 秒,用于驱动传递计时器。随着队列的建立,到达速度快于 one-half 秒 debounceInterval 的元素将被丢弃,而到达速度低于 debounceInterval 的元素将传递给 Publisher/sink(receiveValue:) 运算符。


let bounces:[(Int,TimeInterval)] = [
    (0, 0),
    (1, 0.25),  // 0.25s interval since last index
    (2, 1),     // 0.75s interval since last index
    (3, 1.25),  // 0.25s interval since last index
    (4, 1.5),   // 0.25s interval since last index
    (5, 2)      // 0.5s interval since last index
]


let subject = PassthroughSubject<Int, Never>()
cancellable = subject
    .debounce(for: .seconds(0.5), scheduler: RunLoop.main)
    .sink { index in
        print ("Received index \(index)")
    }


for bounce in bounces {
    DispatchQueue.main.asyncAfter(deadline: .now() + bounce.1) {
        subject.send(bounce.0)
    }
}


// Prints:
//  Received index 1
//  Received index 4
//  Received index 5


//  Here is the event flow shown from the perspective of time, showing value delivery through the `debounce()` operator:


//  Time 0: Send index 0.
//  Time 0.25: Send index 1. Index 0 was waiting and is discarded.
//  Time 0.75: Debounce period ends, publish index 1.
//  Time 1: Send index 2.
//  Time 1.25: Send index 3. Index 2 was waiting and is discarded.
//  Time 1.5: Send index 4. Index 3 was waiting and is discarded.
//  Time 2: Debounce period ends, publish index 4. Also, send index 5.
//  Time 2.5: Debounce period ends, publish index 5.

可用版本

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

相关用法


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