Throttle massive number of inputs in a single drop of one line API.

Overview

Throttler

Icon credits: Lorc, Delapouite & contributors

Throttler

Throttler is a library that throttles unnecessarily repeated and
massive inputs until the last in a single drop of one liner API.

How Throttler works in Yotube


How to use

Just drop it.

import Throttler

for i in 1...1000 {
    Throttler.go {
        print("go! > \(i)")
    }
}

// go! > 1000

Throttler


How to use in Yotube


Use case

While it is originally developed to solve the problem where vast number of user typing input
involving CPU intensive tasks have be to performed repeatedly and constantly
on HLVM,

A common problem that Throttler can solve is
a user taps a button that requests asynchronous network call a massive number of times
within few seconds.

With Throttler,

import UIKit

import Throttler

class ViewController: UIViewController {
    @IBOutlet var button: UIButton!
    
    var index = 0
    
    /********
    Assuming your users will tap the button, and 
    request asyncronous network call 10 times(maybe more?) in a row within very short time nonstop.
    *********/
    
    @IBAction func click(_ sender: Any) {
        print("click1!")
        
        Throttler.go {
        
            // Imaging this is a time-consuming and resource-heavy task that takes an unknown amount of time!
            
            let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
            let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
                guard let data = data else { return }
                self.index += 1
                print("click1 : \(self.index) :  \(String(data: data, encoding: .utf8)!)")
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

Output:

click1!
click1!
click1!
click1!
click1!
click1!
click1!
click1!
click1!
click1!
2021-02-20 23:16:50.255273-0500 iOSThrottleTest[24776:813744] 
click1 : 1 :  {
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Without Throttler

class ViewController: UIViewController {
    @IBOutlet var button: UIButton!
    
    var index = 0
    
    /********
    Assuming your users will tap the button, and 
    request asyncronous network call 10 times(maybe more?) in a row within very short time nonstop.
    *********/
    
    @IBAction func click(_ sender: Any) {
        print("click1!")
        
        // Imaging this is a time-consuming and resource-heavy task that takes an unknown amount of time!
        
        let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
            self.index += 1
            print("click1 : \(self.index) :  \(String(data: data, encoding: .utf8)!)")
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

if you don't use Throttler, Output is as follows:

/* 
click1!
2021-02-20 23:16:50.255273-0500 iOSThrottleTest[24776:813744] 
click1 : 1 :  {
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
click1!
2021-02-20 23:16:50.255273-0500 iOSThrottleTest[24776:813744] 
click1 : 1 :  {
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
click1!
2021-02-20 23:16:50.255273-0500 iOSThrottleTest[24776:813744] 
click1 : 1 :  {
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
click1!
2021-02-20 23:16:50.255273-0500 iOSThrottleTest[24776:813744] 
click1 : 1 :  {
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
.......
......
.....
...
..
.
Your server will start to cry!
😂😂😂

*/

Fundamentally, Throttler can be used to solve various type of problems
related to any repeated and continuous input issue
usually iOS software engineers usually want to avoid.

It is a common situation I can meet in my daily work.
Think about how many lines you need to write without Throttler
to solve these repeatedly tedious and error-prone task!

Why made?

Is it only me who always realized later on iOS I did not validate continuous and repeated input of users (who rapidly bash buttons like tap tap tap, click click click really in a 10 times in a row in few seconds) requesting pretty heavy HTTP request or some resource consuming task? and QA told me please it needs to be controlled on front-end in the first place.
After that, I always repeatedly used to implement this task using DispatchWorkItem or Combine, Timer with isUserInteractionEnabled flags or
even worse, UIApplication.shared.beginIgnoringInteractionEvents()
UIApplication.shared.endIgnoringInteractionEvents() things like that... ( I know it should be only used when you have really no time under serious pressure)

Again, this time while doing my own project, I met this issue again.

So, I made up my mind to build my own yesterday.

Advantages Versus Combine, RxSwift Throttle and Debounce

  • Concise API, one liner, no brainer
  • DispatchWorkItem does the job here. It can cancel http request not initiated out of box.
  • Backward compatibility. Combine needs iOS 13 / macOS Catalina and its new runtime to work. There is no backward compatibility to earlier versions of their operating systems planned. (currently we are living 2021 though...;)

Requirements

  • Swift 5.3+

Installation

Swift Package Manager

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

Contact

[email protected]

https://boraseoksoon.com

https://hlvm.co.kr

Pull requests are warmly welcome as well.

License

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

You might also like...
A thread safe throttle written in Swift

SwiftThrottle - A thread safe throttle written in Swift licensed under MIT. Introduction This throttle is intended to prevent the program from crashing

Build your own 'AirTags' 🏷 today! Framework for tracking personal Bluetooth devices via Apple's massive Find My network.
Build your own 'AirTags' 🏷 today! Framework for tracking personal Bluetooth devices via Apple's massive Find My network.

OpenHaystack is a framework for tracking personal Bluetooth devices via Apple's massive Find My network.

MVVM + FLUX iOS Instagram client  in Swift, eliminates Massive View Controller in unidirectional event/state flow manner
MVVM + FLUX iOS Instagram client in Swift, eliminates Massive View Controller in unidirectional event/state flow manner

CZInstagram MVVM + FLUX iOS Instagram client in Swift, eliminates Massive View Controller in unidirectional event/state flow manner. Unidirectional Da

TwilioChat_iOS - Twilio iOS SDK Implementaion Chat one-one Chat One-Many (Group)

TwilioChat_iOS - Twilio iOS SDK Implementaion Chat one-one Chat One-Many (Group) - Add Participant - Remove Participant Send Attachment Image Android - iOS Tested iOS - iOS Tested iOS - Android Tested React to Message, Delete a Message Read, Delivered, Sent Delete a Conversation Unread Messages Filter

A framework to validate inputs of text fields and text views in a convenient way.

FormValidatorSwift The FormValidatorSwift framework allows you to validate inputs of text fields and text views in a convenient way. It has been devel

Define and chain Closures with Inputs and Outputs

Closure Define and chain Closures with Inputs and Outputs Examples No Scoped State let noStateCount = ClosureString, String { text in String(repea

A framework to validate inputs of text fields and text views in a convenient way.

FormValidatorSwift The FormValidatorSwift framework allows you to validate inputs of text fields and text views in a convenient way. It has been devel

Merges a given number of PDF files into one file using the PDFKit framework

Titanium iOS PDF Merge Merges a given number of PDF files into one file using the PDFKit framework Requirements iOS 11+ Titanium SDK 9+ API's Methods

A drop in single image picker.

PHSingleImagePicker A low memory, single image picker wrapper that provide a significant smaller file size while also preserve high image quality. Int

Anchorage - Single file UIView drag and drop system
Anchorage - Single file UIView drag and drop system

anchorage Single file UIView drag and drop system anchors.mp4 License Copyright

A debug log framework for use in Swift projects. Allows you to log details to the console (and optionally a file), just like you would have with NSLog() or print(), but with additional information, such as the date, function name, filename and line number. A debug log framework for use in Swift projects. Allows you to log details to the console (and optionally a file), just like you would have with NSLog() or print(), but with additional information, such as the date, function name, filename and line number. This
This "Calculator" application is a simple one screen design of calculator screen i have made this single screen design application just to practice AutoLayout concepts.

Calculator Layout This "Calculator" application is a simple one screen design of calculator screen i have made this single screen design application j

Lightweight touch visualization library in Swift. A single line of code and visualize your touches!
Lightweight touch visualization library in Swift. A single line of code and visualize your touches!

TouchVisualizer is a lightweight pure Swift implementation for visualising touches on the screen. Features Works with just a single line of code! Supp

SSToastMessage is written purely in SwiftUI. It will add toast, alert, and floating message view over the top of any view. It is intended to be simple, lightweight, and easy to use. It will be a popup with a single line of code.
SSToastMessage is written purely in SwiftUI. It will add toast, alert, and floating message view over the top of any view. It is intended to be simple, lightweight, and easy to use. It will be a popup with a single line of code.

SSToastMessage SSToastMessage is written in SwiftUI. It will add toast, alert, and floating message view over the top of any view. It is intended to b

Droar is a modular, single-line installation debugging window
Droar is a modular, single-line installation debugging window

Droar is a modular, single-line installation debugging window. Overview The idea behind Droar is simple: during app deployment stages, adding quick ap

Create gradients and blur gradients without a single line of code
Create gradients and blur gradients without a single line of code

EZYGradientView is a different and unique take on creating gradients and gradients with blur on the iOS platform. The default CAGradientLayer implemen

Convert Countries, Country Codes, Continents,... with a single line of code.
Convert Countries, Country Codes, Continents,... with a single line of code.

iOS · macOS · watchOS · tvOS A pure Swift library that allows you to easily convert Countries to Country Codes and Country Codes to Countries. There i

Lightweight touch visualization library in Swift. A single line of code and visualize your touches!
Lightweight touch visualization library in Swift. A single line of code and visualize your touches!

TouchVisualizer is a lightweight pure Swift implementation for visualising touches on the screen. Features Works with just a single line of code! Supp

Comments
Owner
Jang Seoksoon
Programmer in Toronto 🇺🇸 ⇄ 🇰🇷 ⇄ 🇨🇦
Jang Seoksoon
Swift TableView pagination with async API request.

SwiftTableViewPagination Swift TableView pagination with async API request. Output UML Create puml file. $ cd SwiftTableViewPagination/scripts/swiftum

y-okudera 1 Dec 26, 2021
PixabayImageSearchSample - SwiftUI + LazyVGrid + Pixabay API + Codable + sync/async Sample

PixabayImageSearchSample SwiftUI + LazyVGrid + Pixabay API + Codable + sync/asyn

null 3 Nov 23, 2022
Slack message generator and API client, written in Swift with Result Builders and Concurrency

Slack Message Client This package provides a Swift object model for a Slack Block Kit message, as well as a Result Builder convenience interface for e

Mike Lewis 2 Jul 30, 2022
Automatically generate GraphQL queries and decode results into Swift objects, and also interact with arbitrary GitHub API endpoints

GitHub API and GraphQL Client This package provides a generic GitHub API client (GithubApiClient) as well as Codable-like GitHub GraphQL querying and

Mike Lewis 4 Aug 6, 2022
TextFieldFormatter - Simple Text Formatter (Credit Card Number, Phone Number, Serial Number etc.)

TextFieldFormatter Simple Text Formatter (Credit Card Number, Phone Number, Seri

Anıl ORUÇ 4 Apr 4, 2022
This little app aims to help teach me how to implement more then one API in one single application in a reusable and properly structured manner.

LilAPI App News & Weather This little API app combines two of Jordan Singers Lil Software API's into one app. The goal with this app was to learn how

hallux 1 Oct 13, 2021
Simple command line utility for switching audio inputs and outputs on macOS

Switch Audio Simple command line utility for switching audio inputs and outputs

Daniel Hladík 3 Nov 22, 2022
NumberMorphView a view like label for displaying numbers which animate with transition using a technique called number tweening or number morphing.

NumberMorphView a view like label for displaying numbers which animate with transition using a technique called number tweening or num

Abhinav Chauhan 1.6k Dec 21, 2022
A simple solution to show a toast message by writing single one line of code

easySwiftToast A very simple solution to show a toast message by writing single one line of code. Installation easySwiftToast is available through Coc

wajeehulhassan 7 May 13, 2022
Monitor and terminate/throttle CPU hogging processes in iOS

Vedette Monitor and terminate/throttle CPU hogging processes in iOS Vedette is a CPU usage monitoring tweak for processes in iOS like apps and daemons

null 13 Dec 22, 2022