Home > AI > IOS > Combine >

throttle(for:scheduler:latest:)

Example 1 (Apple Official)

let cancellable = Timer.publish(every: 3.0, on: .main, in: .default).autoconnect()
    .print("\(Date().description)")
    .throttle(for: 10.0, scheduler: RunLoop.main, latest: true)
    .sink(
        receiveCompletion: { print ("Completion: \($0).") },
        receiveValue: { print("Received Timestamp \($0).") }
     )

Example 2: capture the first element in this time interval


class Demo10 {
    var cancellables = Set< AnyCancellable>()
    
    func example(of: String) {
        let pub = PassthroughSubject<String,Never>()

        let Hello: [(TimeInterval, String)] = [
            (0.0, "H"),
            (0.1, "He"),
            (0.2, "Hel"),
            (0.3, "Hell"),
            (0.5, "Hello"),
            (0.6, "Hello "),
            (2.0, "Hello W"),
            (2.1, "Hello Wo"),
            (2.2, "Hello Wor"),
            (2.4, "Hello Worl"),
            (2.5, "Hello World")
        ]



        pub
        .throttle(for: .seconds(1), scheduler: DispatchQueue.main, latest: false)
        .sink { data in
            print( data)
            }
        .store(in: &cancellables)
        
        pub.send("fgggd")
        Hello.forEach { (delay, str) in
            DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
                pub.send(str)
            }
            pub.send(str)
        }
    }
}

let d = Demo10()
d.example(of: "good")

Leave a Reply