當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Swift Result.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大神的英文原創作品 Result.Publisher debounce(for:scheduler:options:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。