1

Consider the following code:

class MyController: NSObject, ObservableObject {

    //...

    @Published var myRapidlyChangingVar: MyEnum? = nil

    //...

    func calledAtHighFrequencyByExternalEvents(value: MyEnum) {
        myRapidlyChangingVar = value
    }
}

The value of myRapidlyChangingVar needs to be set to nil if no calls to calledAtHighFrequencyByExternalEvents() have been made for 1 second.

What is the simplest and cleanest approach to adopt to achieve this?

Strikes me as the sort of thing which Reactive programming should make incredibly simple, but unsure where to start or what to search for.

0

1 Answer 1

3

You can easily achive this with a debounce(for:scheduler:options:)

let cancellable = myRapidlyChangingVar
    .compactMap { $0 }
    .debounce(for: .seconds(1), scheduler: DispatchQueue.main)
    .sink { [weak self] _ in self?.myRapidlyChangingVar = nil }
}

Debounce has a fairly similar sibiling throttle(for:scheduler:latest:)

You can read more about both in this blogpost.

2
  • 1
    Many thanks for this Witek - it did indeed work. Another developer commented that the call to compactMap() should be moved before debounce() for performance reasons. Nov 20, 2021 at 16:32
  • Happy it worked out for you. Good point with moving the compactMap, I will update my answer :) Nov 20, 2021 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.