Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct syntax for using Publishers.debounce() in Swift Combine?

In Apple's 2019 WWDC video Swift Combine in Practice, they demonstrate using a debounce publisher to slow down the rate of messages.

return $username
  .debounce(for: 0.5, scheduler: RunLoop.main)
  .removeDuplicates()
  .eraseToAnyPublisher()

However, anytime I attempt to use it in a similar fashion, I get the following error:

Cannot invoke 'debounce' with an argument list of type '(for: Double, scheduler: RunLoop)'

The debounce() signature is:

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

SchedulerTimeType.Stride appears to be initializable with a numeric but it's not working for me or my inexperience with Swift Generics is on display.

What is the correct way to call this?

Edit

Duplicate of this question...

Searching for generic words like "Combine" is, for now, rather challenging...

macOS 10.15, Xcode 11

like image 292
kennyc Avatar asked Jun 13 '19 11:06

kennyc


People also ask

What is debounce combine?

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.

What is publisher in combine?

Within the world of Combine, an object that emits such asynchronous values and events is called a publisher, and although the framework does ship with quite a large number of built-in publisher implementations, sometimes we might want to build our own, custom ones in order to handle specific situations.

What is debounce Swift?

debounce() listens to user events and publishes if there is a delay of 0.5s in user activity. Subscriber receives the event of the search text which then is queried against the actual records.

What is combine framework in Swift?

The Combine framework provides a declarative Swift API for processing values over time. These values can represent many kinds of asynchronous events. Combine declares publishers to expose values that can change over time, and subscribers to receive those values from the publishers.


1 Answers

The documented debounce<S> operator accepts type S.SchedulerTimeType.Stride which looks something like this:

let sub = NotificationCenter.default
    .publisher(for: NSControl.textDidChangeNotification, object: filterField)
    .debounce(for: .milliseconds(500), scheduler: RunLoop.main)
    .subscribe(on: RunLoop.main)
    .assign(to:\MyViewModel.filterString, on: myViewModel)
like image 107
chris stamper Avatar answered Sep 17 '22 18:09

chris stamper