GithubHelp home page GithubHelp logo

boraseoksoon / throttler Goto Github PK

View Code? Open in Web Editor NEW
134.0 5.0 19.0 125 KB

One Line to throttle, debounce and delay: Say Goodbye to Reactive Programming such as RxSwift and Combine.

License: MIT License

Swift 100.00%
swift ios swiftui macos cocoa asynchronous-programming combine dispatchqueue throttle throttle-requests async throttler input validation validation-library function swift-package-manager dispatchworkitem uikit foundation

throttler's Introduction

Throttler

Icon credits: Lorc, Delapouite & contributors

Throttler

Drop one line to use throttle, debounce, and delay with full thread safety: say goodbye to reactive programming like RxSwift and Combine.

At a glance

import Throttler

debounce {
    print("debounce 1 sec")
}

throttle {
    print("throttle 1 sec")
}

delay {
    print("delay 1 sec")
}

๐Ÿ’ฅ Basic Usage in SwiftUI

Here's how you can quickly get started.

import SwiftUI
import Throttler

struct ContentView: View {
    var body: some View {
        VStack {
            Button(action: {
                for i in 1...10000000 {
                    throttle {
                        print("throttle: \(i)")
                    }
                }
            }) {
                Text("throttle")
            }
            // Expected Output: Will print "throttle : \(i)" every 1 second (by default)

            Button(action: {
                delay {
                    print("delayed 2 seconds")
                }
            }) {
                Text("delay")
            }
            // Expected Output: Will print "Delayed 2 seconds" after 2 seconds

            Button(action: {
                for i in 1...10000000 {
                    debounce {
                        print("debounce \(i)")
                    }
                }
            }) {
                Text("debounce")
            }
            // Expected Output: Will print "debounce" only after the button has not been clicked for 1 second
        }
    }
}

๐ŸŒŸ Features

  • Throttle: Limit how often an operation can be triggered over time. Thanks to Swift's actor model, this operation is thread-safe.
  • Debounce: Delay the execution of an operation until a certain time has passed without any more triggers. This operation is also thread-safe, courtesy of Swift's actor model.
  • Delay: Execute an operation after a certain amount of time. With Swift's actor model, you can rest assured that this operation is thread-safe too.

๐Ÿฆพ Thread Safety

All of these operations are executed in a thread-safe manner, leveraging the Swift actor model. This guarantees safe access and modification of shared mutable state within the closure of throttle, debounce, and delay functions, regardless of the number of threads involved.

Feed any shared resource into them (debounce, throttle, debounce). The functions will handle everything out of box.

import Foundation

/* a simple thread safe test. */

var a = 0

DispatchQueue.global().async {
    for _ in Array(0...10000) {
        throttle(.seconds(0.1), by: .ownedActor) {
            a+=1
            print("throttle1 : \(a)")
        }
    }
}

DispatchQueue.global().async {
    for _ in Array(0...100) {
        throttle(.seconds(0.01), by: .ownedActor) {
            a+=1
            print("throttle2 : \(a)")
        }
    }
}

DispatchQueue.global().async {
    for _ in Array(0...100) {
        throttle(.seconds(0.001), by: .ownedActor) {
            a+=1
            print("throttle3 : \(a)")
        }
    }
}

DispatchQueue.global().async {
    for _ in Array(0...100) {
        debounce(.seconds(0.001), by: .ownedActor) {
            a+=1
            print("debounce1 : \(a)")
        }
    }
}

//throttle3 : 1
//throttle3 : 2
//throttle3 : 3
//throttle3 : 4
//throttle3 : 5
//throttle3 : 6
//throttle3 : 7
//throttle3 : 8
//throttle3 : 9
//throttle3 : 10
//throttle3 : 11
//debounce1 : 12
//throttle3 : 13
//throttle2 : 14
//throttle1 : 15
//throttle1 : 16
//throttle1 : 17
//throttle1 : 18
//throttle1 : 19
//throttle1 : 20
//throttle1 : 21
//throttle1 : 22
//throttle1 : 23
//throttle1 : 24
//throttle1 : 25
//throttle1 : 26
//throttle1 : 27

/// safe from race condition => โœ…
/// safe from data race      => โœ…

๐Ÿš€ Advanced Features for Throttler

Throttler stands out not just for its advanced features, but also for its incredibly simple-to-use API. Here's how it gives you more, right out of the box, with just a one-liner closure:

Throttle Options

  1. default: Standard throttling behavior without any fancy tricks. Simply include the throttle function with a one-liner closure, and you're good to go.
  2. ensureLast: Ensures the last call within the interval gets executed. Just a single line of code.

Debounce Options

  1. default: Standard debounce behavior with just a one-liner closure. Include the debounce function, and it works like a charm.
  2. runFirst: Get instant feedback with the first call executed immediately, then debounce later. All of this with a simple one-liner.

DebounceOptions

  1. default: The standard debounce behavior by default.
/// by default: duration 1 sec and default debounce (not runFirst)

for i in Array(0...100) {
    debounce {
        print("debounce : \(i)")
    }
}

// debounce : 100
  1. runFirst: Executes the operation immediately, then debounces subsequent calls.
/// Expected Output: Executes a first task immediately, then debounce only after 1 second since the last operation.

for i in Array(0...100) {
    debounce(.seconds(2), option: .runFirst) {
        print("debounce : \(i)")
    }
}

// debounce : 1        => ๐Ÿ’ฅ
// debounce : 100

ThrottleOptions

Options Explained

  1. default: The standard throttle behavior.
/// Throttle and executes once every 1 second.

for i in 1...100000 {
    throttle {
        print("throttle: \(i)")
    }
}

// throttle: 0
// throttle: 41919
// throttle: 86807
  1. ensureLast: Guarantees that the last call within the interval will be executed.
/// Guarantees the last call no matter what even after a throttle duration and finished.

for i in 1...100000 {
    throttle(option: .ensureLast) {
        print("throttle : \(i)")
    }
}

// throttle : 0 
// throttle : 16363 
// throttle : 52307
// throttle : 74711
// throttle : 95747
// throttle : 100000    => ๐Ÿ’ฅ

Throttler makes it extremely simple and easy to use advanced features with just a one-liner, unlike RxSwift and Combine where custom implementations are often required.

Comparison with RxSwift and Combine for the advanced options in code

  • RxSwift:
import RxSwift

let disposeBag = DisposeBag()
Observable.from(1...100000)
    .throttle(RxTimeInterval.milliseconds(500), latest: false, scheduler: MainScheduler.instance)
    .subscribe(onNext: { i in
        print("throttle : \(i)")
    })
    .disposed(by: disposeBag)
  • Combine:

Throttle options

import Combine

var cancellables = Set<AnyCancellable>()
Publishers.Sequence(sequence: 1...100000)
    .throttle(for: .milliseconds(500), scheduler: DispatchQueue.main, latest: false)
    .sink(receiveValue: { i in
        print("throttle : \(i)")
    })
    .store(in: &cancellables)
  • Throttler:
import Throttler

throttle {
    print("hi")
}

Advantages over Combine and RxSwift's Throttle and Debounce

  • Simplicity: These functions are designed to be straightforward and easy to use. With just a single line of code, you can have them up and running.
  • Out-of-the-Box Thread Safety: Simply pass any shared resource into the debounce, throttle, or delay functions without any concerns. The implementation leverages the Swift actor model, providing robust protection against data races for mutable states. This ensures that you can safely access and modify shared mutable state without any worries about thread safety. It will handle everything in a thread-safe manner out of box.
  • No Need for Reactive Programming: If you prefer not to use reactive programming paradigms, this approach provides an excellent alternative. It allows you to enjoy the benefits of throttling and debouncing without having to adopt a reactive programming style.

โš ๏ธ Important Note on Identifiers parameters for debounce and throttle

Highly Recommended: While the functions are intentionally designed to run out of the box without specifying an identifier in favor of brevity, it is strongly recommended to provide a custom identifier for debounce and throttle operations for better control and organization.

Example with Custom Identifier

// simple and come in handy by default

throttle {
    print("simple")
}

// recommended

throttle(identifier: "custom_throttle_id") {
    print("This is a recommended way of using throttled.")
}

// simple and come in handy by default

debounce {
    print("simple")
}

// recommended

debounce(.seconds(2), identifier: "custom_debounce_id") {
    print("This is a recommended way of using debounced.")
}

Throttler V2.0.0 - Actor-based Update

What's New in V2.0.0

In favor of new Swift concurrency, this release completely relies on and leverages the new actor model introduced in Swift 5.5 for better performance and safer code execution. The previous versions that used standard Swift methods for task management such as GCD has been completely removed as deprecated to emphasize the use of the actor in a unified way.

(Please be aware that the minimum version requirement has been raised to iOS 16.0, macOS 13.0, watchOS 9.0, and tvOS 16.0.)

Struct based (Deprecated)

As of V2.0.0, struct based way was removed as deprecated in favor of Swift actor type. Please migrate to functions. (throttle, debounce and delay)

Requirements

iOS 16.0, macOS 13.0, watchOS 9.0, tvOS 16.0

Installation

Swift Package Manager

To use the latest V2.0.9 version, add the package to your Package.swift:

dependencies: [
    .package(url: "https://github.com/YourRepo/Throttler.git", .upToNextMajor(from: "2.0.9"))
]

or in Xcode:

  • File > Swift Packages > Add Package Dependency
  • Add https://github.com/boraseoksoon/Throttler.git
  • Click Next.
  • Done.

Contact

[email protected]

Pull requests are warmly welcome as well.

License

Throttler is released under the MIT license. See LICENSE for details.

throttler's People

Contributors

boraseoksoon avatar nylki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

throttler's Issues

iOS 16+

Its iOS 16+ only.
Please put it on the readme...

debounce delay more than design

testcase:
func testDebounce() {
let exp = self.expectation(description: "Task")
Task {
var runCount = 0
for i in 0..<10 {
debounce(option: .runFirst) {
print(Date().printFormat(), "debounce test: (i)")
runCount += 1
}
try? await Task.sleep(for: .milliseconds(600))
}
// exp.fulfill()
}
self.wait(for: [exp], timeout: 10)
}
result:
2024-04-28 09:49:41.257 debounce test: 0
2024-04-28 09:49:41.879 debounce test: 1
2024-04-28 09:49:42.289 debounce test: 0
2024-04-28 01:49:42 +0000 task is cancelled
2024-04-28 01:49:43 +0000 task is cancelled
2024-04-28 01:49:43 +0000 task is cancelled
2024-04-28 01:49:44 +0000 task is cancelled
2024-04-28 01:49:44 +0000 task is cancelled
2024-04-28 01:49:45 +0000 task is cancelled
2024-04-28 01:49:46 +0000 task is cancelled
2024-04-28 01:49:46 +0000 task is cancelled
2024-04-28 09:49:47.855 debounce test: 9

two problem:

  1. first task run two times
  2. task delay more than 1 second(duration)

the debounce expect in duration only trigger only once, but now, it delay much more time than duration

Race condition in `throttle()`

I faced a race condition using func throttle(): it is possible to reach await actor.run(operation) multiple times in less time than the specified duration parameter.

Nothing prevents throttle() to be called simultaneously from different threads. Throttler being an actor, this is safe but the race condition is still here: let lastDate = lastAttemptDate[identifier] can be set from 2 (or more) different threads before self.lastAttemptDate[identifier] = Date() is reached.

When this happens, the operation is called multiple times in a row, breaking the throttle contract.

I'll try to suggest a fix later.

Throttle runs first request with a delay

I set throttle for every 3 seconds, but have a delay for 3 seconds for the first request. Was it intended that way?

        print("\(Date().toString(format: "HH:mm:ss")): Begin")
        for i in 1...10000 {
            throttle(.seconds(3)) {
                print("\(Date().toString(format: "HH:mm:ss")): throttle: \(i)")
            }
        }

Screenshot 2024-03-13 at 11 01 51

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.