[WIP] First pass at some documentation for AsyncChannel (#91)

* First pass at some documentation for AsyncChannel

* Apply suggestions from code review

Co-authored-by: Chris Adamson <invalidname@gmail.com>

* Manually line break docs

Co-authored-by: Chris Adamson <invalidname@gmail.com>
This commit is contained in:
Philippe HauslerandChris Adamson authored and GitHub committed 2022-03-18 11:39:45 -07:00
1 parent 37ad908591
commit bcd0ee1e50
2 files changed
+19

No files matched your search

@@ -9,7 +9,16 @@
//
//===----------------------------------------------------------------------===//
/// A channel for sending elements from on task to another with back pressure.
///
/// The `AsyncChannel` class is intended to be used as a communication type between tasks,
/// particularly when one task produces values and another task consumes those values. The back
/// pressure applied by `send(_:)` and `finish()` via the suspension/resume ensure that
/// the production of values does not exceed the consumption of values from iteration. Each of these
/// methods suspends after enqueuing the event and is resumed when the next call to `next()`
/// on the `Iterator` is made.
public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
/// The iterator for a `AsyncChannel` instance.
public struct Iterator: AsyncIteratorProtocol, Sendable {
let channel: AsyncChannel<Element>
var active: Bool = true
@@ -18,6 +27,7 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
self.channel = channel
}
/// Await the next sent element or finish.
public mutating func next() async -> Element? {
guard active else {
return nil
@@ -98,6 +108,7 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
let state = ManagedCriticalState(State())
/// Create a new `AsyncChannel` given an element type.
public init(element elementType: Element.Type = Element.self) { }
func establish() -> Int {
@@ -180,14 +191,19 @@ public final class AsyncChannel<Element: Sendable>: AsyncSequence, Sendable {
continuation?.resume(with: result)
}
/// Send an element to an awaiting iteration. This function will resume when the next call to `next()` is made.
/// If the channel is already finished then this returns immediately
public func send(_ element: Element) async {
await _send(.success(element))
}
/// Send a finish to an awaiting iteration. This function will resume when the next call to `next()` is made.
/// If the channel is already finished then this returns immediately
public func finish() async {
await _send(.success(nil))
}
/// Create an `Iterator` for iteration of an `AsyncChannel`
public func makeAsyncIterator() -> Iterator {
return Iterator(self)
}