Skip to content

A library to serialize async `Task`. Also support `AsyncThrowingStream`.

License

Notifications You must be signed in to change notification settings

rickymohk/SwiftTaskQueue

Repository files navigation

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)")
    }
}

About

A library to serialize async `Task`. Also support `AsyncThrowingStream`.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages