0

Overview

  • I have a function f1 which is non-async function.
  • f1 gets called multiple times and I have no control over the calling of f1
  • When f1 gets called I would like to invoke an async function f2

Aim:

  • I would like f2 to complete before the next f2 executes

Question:

  • How can I ensure f2 executes in sequence? (sample code below)
//I have no control over f1
//f1 can get called multiple times in quick succession.
func f1() {
    Task {
        try await f2() // Next time f1 gets called it should wait for the previous f2 to complete then should execute f2
    }
}

func f2() async throws {}
user1046037
  • 16,755
  • 12
  • 92
  • 138
  • 2
    Put `f2` into an actor. What you're describing is exactly what an actor is for. – matt Dec 07 '21 at 16:07
  • 2
    Actors are suitable if data race is a primary concern. If the order of execution is more of a concern, then Combine or OperationQueue would be more suitable. – timbre timbre Dec 07 '21 at 16:51
  • Thanks a lot Matt and Kiril and, very valuable points, exactly what I was looking for and was very helpful in understanding what tool to use for what purpose – user1046037 Dec 08 '21 at 00:32

0 Answers0