Skip to content

Instantly share code, notes, and snippets.

View NikolaiRuhe's full-sized avatar

Nikolai Ruhe NikolaiRuhe

View GitHub Profile
func testRequestCancellation() async throws {
// Used to synchronize unit test with request task.
let meeting = TaskMeeting()
// This request just waits for the unit test in its handler.
let sut = Request(responseHandler: { _ in
try? await meeting.rendezvous {}
})
import XCTest
import SwiftUI
final class CaptureListTests: XCTestCase {
func testCaptureList() throws {
withBound("foo") { $boundValue in
print("value: \(boundValue), binding type: \(type(of: $boundValue))")
}
}
extension Binding where Value: MutableCollection, Value.Element: Identifiable {
subscript(_ id: Value.Element.ID) -> Binding<Value.Element> {
let index = wrappedValue.firstIndex { $0.id == id }
guard let index else {
fatalError("id not found: \(id)")
}
return self[index]
}
}
actor A {
var iterator: AsyncStream<Void>.Iterator
init() {
iterator = AsyncStream<Void> { _ in }.makeAsyncIterator()
}
func f() async {
await iterator.next() // Cannot call mutating async function 'next()' on actor-isolated property 'iterator'
}
}
import XCTest
final class BarrierTests: XCTestCase {
func test() async {
let subsystem = Subsystem()
await withTaskGroup(of: Void.self) { group in
for index in 0 ..< 100 {
group.addTask { subsystem.performWork(id: index) }
}
@NikolaiRuhe
NikolaiRuhe / CancellingContinuation.swift
Last active May 5, 2025 12:52
A continuation that resumes automatically when the suspended task is cancelled.
import os.lock
/// `CancellingContinuation` is built on top of `CheckedContinuation` and
/// provides some additional features. It can be used as a drop-in replacement,
/// providing a similar API.
///
/// ## Automatic cancellation
/// When the suspended task is cancelled the continuation is automatically
/// resumed with a `CancellationError`. After that, normally resuming the
/// continuation from client is silently ignored.
@NikolaiRuhe
NikolaiRuhe / gist:36384157d59c392c0a36331886198fbd
Created August 14, 2025 16:44
A property wrapper that creates an AsyncStream yielding values when the property is set.
import os
@propertyWrapper
public struct Streaming<Wrapped: Sendable> {
public var wrappedValue: Wrapped {
get { value }
set {
value = newValue
let continuations = protectedContinuations.withLock { $0.values }
for continuation in continuations {
@NikolaiRuhe
NikolaiRuhe / Streaming.swift
Last active September 22, 2025 10:11
A property wrapper that creates an AsyncStream yielding values when the property is set.
import os
/// A property wrapper that turns a stored property into an async stream.
///
/// Semantics are similar to Combine's `CurrentValueSubject`. Multiple clients
/// are allowed. Each client gets an individual stream.
///
/// The wrapped value itself inherits isolation from the surrounding type.
/// The stream is nonisolated, so it can be accessed from any execution context.
///