Skip to content

Files

Latest commit

author
rickymo
Mar 10, 2023
0016e90 · Mar 10, 2023

History

History
75 lines (58 loc) · 1.93 KB

README.md

File metadata and controls

75 lines (58 loc) · 1.93 KB

SwiftTaskQueue

A library to serialize async Task. Also support AsyncThrowingStream.

Swift Version Build Status License

This library helps organizing async tasks into a queue, making sure multiple tasks are executed one by one. This could be handy when multiple tasks are being fired at arbitary moment but must not run concurrently.

Installation

Add this project on your Package.swift

import PackageDescription

let package = Package(
    dependencies: [
        .package(url: "https://github.com/rickymohk/SwiftTaskQueue.git", .branch("main"))
    ]
)

Usage example

import SwiftTaskQueue

let taskQueue = TaskQueue()

// Call from non-async context, without waiting for result
taskQueue.dispatch {
    // your async code here
}
    
Task{
    
    // Call from async context, waiting for result
    let result = try? await taskQueue.dispatch {
        // your async code here
        // ...
        return "result"
    }

    // Create AsyncThrowingStream in the queue
    let stream = taskQueue.dispatchStream { continuation in
        // your stream builder here
        // ...
        continuation.yield("result")
        // ...
        // remember to call finish when you are done with this stream, otherwise the whole queue will be blocked
        continuation.finish() 
    }
    
    do{
        for try await result in stream
        {
            // use the result from the stream
        }
    }
    catch
    {
        print("stream error \(error)")
    }
}