onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
669 stars 33 forks source link

How to use debounce in Combine in Swift #827

Open onmyway133 opened 2 years ago

onmyway133 commented 2 years ago

I'm trying a simple Future and sink. As long as I have debounce, only receiveCompletion gets called, but not receiveValue

private var bag = Set<AnyCancellable>()

let future = Future<Int, Never> { promise in
    promise(.success(1))
}

future
.debounce(for: .seconds(0.5), scheduler: DispatchQueue.main)
.sink(
    receiveCompletion: { 
         print($0) // Called
    },
    receiveValue: { 
        print($0)  // Not called
    }
)
.store(in: &bag)

Reading debounce

Publishes elements only after a specified time interval elapses between events. This operator is useful to process bursty or high-volume event streams where you need to reduce the number of values delivered to the downstream to a rate you specify.

In the example above, our Publisher only emits 1 single event, that's why it does not work with debounce