i think this is just a confusing consequence of sharing the same underlying AsyncStream across multiple 'consumers'. the problem with doing this without explicitly replicating the stream's elements per 'consumer' is that delivery order can be arbitrary depending on the configuration (see my confused reaction upon initially learning about this behavior).
so what i think is going on in this case is that there's the one 'source' stream:
let integers = AsyncStream<Int> { continuation in
Task {
var size = 10
while !Task.isCancelled && size > 0 {
try? await Task.sleep(for: .milliseconds(300))
continuation.yield(size)
size -= 1
}
continuation.finish()
}
}
and then the code that transforms the source sequence:
let evens = integers.compactMap { i in
i % 2 == 0 ? i : nil
}
let odds = integers.compactMap { i in
i % 2 == 0 ? nil : i
}
and lastly, there's the code that actually performs the iteration:
await withTaskGroup { group in
group.addTask {
for await o in odds {
print("odd:", o)
}
print("Odds done.")
}
group.addTask {
for await e in evens {
print("even:", e)
}
print("Evens done.")
}
await group.waitForAll()
print("Group done.")
}
since the iterating child tasks are concurrent with respect to each other, they will race for the initial consumption. if the odd map sequence 'wins', it will get an even value first, effectively seeing nil. then, due to implementation details of how AsyncStream manages multiple consumers (i think they are FIFO, but it's been a while since i looked closely), the next value will be delivered to the even map sequence. but of course that value will be odd, so that too will return nil. so the sequencing happens to align such that both map sequences effectively filter everything out. of course if the race goes the other way then it 'works'.
if you serialize the child tasks by putting them on the same global actor (not something you'd actually want to do with that API in general), and ensure that even iterator is the first one enqueued:
await withTaskGroup(of: Void.self) { group in
group.addTask { @Sendable @MainActor in
for await e in evens {
print("even:", e)
}
print("Evens done.")
}
group.addTask { @Sendable @MainActor in
for await o in odds {
print("odd:", o)
}
print("Odds done.")
}
await group.waitForAll()
print("Group done.")
}
then i think the output will print the expected, consistent results.
output
even: 10
odd: 9
even: 8
odd: 7
even: 6
odd: 5
even: 4
odd: 3
even: 2
Evens done.
odd: 1
Odds done.
Group done.