Home > Mobile >  How to delay swift property didSet so it only fires once per second
How to delay swift property didSet so it only fires once per second

Time:01-19

Would it be possible to limit didSet, so it only fires once in a time interval, like once every second, and not multiple times in a second? Like some kind of debounce method?

@Published var someProperty: String = "" {didSet {
    Task {
        await someFunction(someParamater: someProperty)
    }
}}

CodePudding user response:

Each @Published property has a Combine publisher under the hood. You can subscribe to this publisher and debounce it like this:

myModel.$someProperty
    .debounce(...)
    .sink { value in
        // Do what you wanted to do in didSet
    }
    .store(in: &cancellables)
  • Related