AsyncSequence vs. Combine Publisher

👍
· Apr 20, 2023 · 2 mins read
AsyncSequence vs. Combine Publisher

AsyncSequence and Combine Publisher are different ways of handling future data. Both of them have rich operators/methods like map, filter, combineLatest etc. to manage the data flow. But what are the differences and which one should we use?

AsyncSequence

AsyncSequence is an evolution of the conception of Sequence in Swift Concurrency, which emits values over time through AsyncIterator. It’s a language feature in Swift, which means, it is available in other platforms like linux and windows etc. Please also note, Swift Async Algorithms package enriches its functionalities while some related basic types and methods can be found in Foundation library.

Combine Publisher

Combine is a Framework from Apple that provides native solution of Reactive programming like Rx family(RxSwift is the most famous one of them before Combine). It’s only available in Apple’s platforms at least now.

Main differences

Different Syntax

With asyncSequence, use for await...in loop to iterate all the values of the sequence like the example from Apple’s document.

for await number in Counter(howHigh: 10) {  
    print(number, terminator: " ")  
}

With Combine, the publisher will send values to its subscribers and the subscribers then get the chance to process the values like the example below from Apple’s document.

let myRange = (0...3)  
cancellable = myRange.publisher  
    .sink(receiveCompletion: { print ("completion: \($0)") },  
          receiveValue: { print ("value: \($0)") })

Blocking vs. non-blocking

Another important difference is, with for await...in loop, the thread will be blocked until all the values from the sequence are processed. Practically all the statements after this loop only get to run after this loop is done.

However, with Combine syntax, the statement in the above example is only to setup the subscription. It immediately finishes and the statements after it will be running afterwards regardless status of the publisher.

How to choose between these two

Using which one is really a personal choice if both of them are suitable for the case as they all work great. But if the app has the potential to be ported to other platforms, might be better to choose AsyncSequence as this is native to Swift language.

Another thing worthy mentioning is that these two are easily be bridged into each other. We can just use values property to get the AsyncSequence out of the publisher. (Note, RxSwift also provides values properties for the observables for the same purpose.)

To convert an AsyncSequence to a Combine publisher, the easiest way is to use a Combine subject(either CurrentValueSubject or PassthroughSubject), which receives the values and sends out values as a publisher.

Comments

Sharing is caring!