Search code examples
iosswiftcombine

Swift: Does AsyncStream work in a subscription-based context?


Unfortunately, I haven't been able to find much documentation on example usages of AsyncSequence, particularly with the AsyncStream implementation, but I'm trying to understand these on a deeper level.

At the moment, I'm interested in converting something like a subscription-based Cancellable that lives for the lifetime of a view controller and reacts to any changes in an observed property.

Is this an appropriate use case for AsyncSequence? From what I understand, you would observe the sequence with a for-in loop, but is it possible to continue watching for changes after the observed property has been updated once, or is it only a one-and-done type of usage?


Solution

  • "Is this an appropriate use case for AsyncSequence" It is exactly the use case for AsyncSequence.

    But wait, there's more! Every Combine publisher has a values property which is an AsyncSequence. If you already have a publisher, there is nothing to "convert". Just use that publisher's values in an async context and away you go.

    Example:

    let timerpub = Timer.publish(every: 1, on: .main, in: .default).autoconnect()
    Task {
        for await value in timerpub.values {
            // do something with `value`! called every second
        }
    }