Skip to content

Commit

Permalink
Add AsyncSequence.collect()
Browse files Browse the repository at this point in the history
  • Loading branch information
jessetipton committed Dec 11, 2022
1 parent 1874715 commit d19009f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
//
// AsyncSequence+Collect.swift
//
//
// Created by Jesse Tipton on 12/10/22.
//

@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension AsyncSequence {
public func collect() async rethrows -> [Element] {
try await reduce(into: [Element]()) { $0.append($1) }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//
// AsyncSequenceCollectTests.swift
//
//
// Created by Jesse Tipton on 12/10/22.
//

import XCTest
import NiceThings

final class AsyncSequenceCollectTests: XCTestCase {
func testCollect() async {
let stream = AsyncStream { continuation in
continuation.yield(1)
continuation.yield(2)
continuation.yield(3)
continuation.finish()
}

let output = await stream.collect()

XCTAssertEqual(output, [1, 2, 3])
}

func testCollectOnThrowingSequence() async throws {
let throwingStream = AsyncThrowingStream { continuation in
continuation.yield(1)
continuation.yield(2)
continuation.yield(3)
continuation.finish()
}

let output = try await throwingStream.collect()

XCTAssertEqual(output, [1, 2, 3])
}
}

0 comments on commit d19009f

Please sign in to comment.