SyncStream

1.1.2

StreamUtilities is a toolbox providing two utilities for working with stream in swift. SyncStream, a class that generates a sequence of values and operates synchronously. BidirectionalStream, a class aims to bring features similar to Python's Generator to Swift.
rockmagma02/StreamUtilities

What's New

1.1.2

2024-04-22T04:55:42Z

What's Changed

  • fix(BidirectionalStream): fix nested stream will cause nested error by @rockmagma02 in #5

Full Changelog: 1.1.1...1.1.2

SyncStream

SyncStream Package provides two classes, One is SyncStream which is similar to the swift AsyncStream but run in synchronous way. The other is BidirectionalSyncStream which is inspired by the generator in python, have the ability to send values back to the stream.

Overview

SyncStream

SyncStream is inspired by Swift's AsyncStream and offers a convenient way to generate a sequence using a closure, without the need to implement the Sequence protocol.

Just like the AsyncStream , the SyncStream also utilizes a class called Continuation to manage the production progress. The Continuation offers two main methods, yield(_:) and finish, similar to those in the AsyncStream, but operates synchronously. If you are familiar with Python, you can consider the SyncStream as a generator.

let stream = SyncStream<Int> { continuation in
    for i in 0..<10 {
        continuation.yield(i)
    }
    continuation.finish()
}

for value in stream {
    print(value, terminator: " ")
}
// 0 1 2 3 4 5 6 7 8 9

BidirectionalSyncStream

Inspired by the generator in python, which can not only use the yield to generate new value, but also can use send to sendback value and use return to throw StopIteration error to stop the stream. The BidirectionalSyncStream is a class that provides the same functionality in Swift.

For more information about the generator in python, See: PEP 255, PEP 342, Doc

let stream = BidirectionalSyncStream<Int, Int, NoneType> { continuation in
    var value = 0
    while true {
        value = continuation.yield(value)
        value += 1
    }
}

try stream.next() // 0 start the stream
try stream.send(5) // 6 send value back to the stream, and get the next value
let stream = BidirectionalSyncStream<Int, Int, String> { continuation in
    var value = 0
    while true {
        value = continuation.yield(value)
        value += 1
        if value == 5 {
            continuation.return("Stop")
        }
    }
}

try stream.next() // 0 start the stream
do {
    try stream.send(4) // Throw StopIteration error
} catch {
    // get return value
    print((error as! StopIteration).value) // "Stop"
}

Contribution

We welcome contributions to HttpX by opening a pull request on GitHub.

License

HttpX is released under the Apache License, Version 2.0.

Description

  • Swift Tools 5.10.0
View More Packages from this Author

Dependencies

Last updated: Thu Oct 17 2024 16:52:49 GMT-0900 (Hawaii-Aleutian Daylight Time)