How to interrupt the awaiting in a `for-await` loop / Swift

217 views Asked by At

I'm wondering how to stop a for-await loop from "awaiting".

Here's the loop. I use it to listen to new Transactions with storekit2:

    transactionListener = Task(priority: .background) { [self] in
        // wait for transactions and process them as they arrive
        for await verificationResult in Transaction.updates {
            if Task.isCancelled { print("canceled"); break }

            // --- do some funny stuff with the transaction here ---
            await transaction.finish()
        }
        print("done")
    }

As you can see, Transaction.updates is awaited and returns a new transaction whenever one is created. When the App finishes, I cancel the loop with transactionListener.cancel() - but the cancel is ignored as the Transaction.updates is waiting for the next transaction to deliver and there's no direct way in the API to stop it (like, e.g. Task.sleep() does)

The issues starts, when I run unit-tests. The listener from a previous test is still listening while the next test is already running. This produces very unreliable test results and crashes our CI/CD pipeline. I nailed it down to the shown piece of code and the described issue.

So, question: Is it possible to interrupt a for-await loop from awaiting? I have something like the Unix/Linux command kill -1 in mind. Any ideas?

0

There are 0 answers