Home > Net >  Alternatives to Kotlin Coroutine in Swift
Alternatives to Kotlin Coroutine in Swift

Time:06-21

I am new to Swift language. I would like to know what is the alternative of wait all tasks to finish before executing the next functions in Swift?

I tried the async/await functions of Swift, but the functions just run in the background instead of waiting until the tasks finish.

Thank you.

func checkData(firstName: String) async {
  Task(priority: .high) {
    await compareFirstName(firstName: firstName)
  }
  
  Task(priority: .low) {
    await uploadFirstName(firstName: firstName)
  }
}

I want the compareFirstName() to finish first, but the uploadFirstName() always finish before the compareFirstName().

CodePudding user response:

What is the alternative of wait all tasks to finish before executing the next functions in Swift?

Generally, DispatchGroup should be adequate to achieve what you are expecting.

For example,

let workQueue = DispatchQueue(label: "workQueue")
let group = DispatchGroup()

// Task 1
group.enter()
API.fetch { data in
   AnotherAPI.fetch(data) {
       group.leave()
   }
}

// Task 2.
group.enter()
Local.persist { localUrl in
   UploaderTask.upload(localUrl) { result in
       group.leave()
   }
}

group.notify(queue: workQueue) {
   // executed after completion of Task 1, Task 2
   sayHi()
}

Alternatively, in your particular case, uploadFirstName() can be sent as a completion block for compareFirstName().

CodePudding user response:

I tried the async/await functions of Swift, but the functions just run in the background instead of waiting until the tasks finish.

Because you wrote your code wrong. Put the awaits into one task:

func checkData(firstName: String) async {
  Task {
    await compareFirstName(firstName: firstName)
    await uploadFirstName(firstName: firstName)
  }
}

Moreover, if checkData is async, you don't need the Task:

func checkData(firstName: String) async {
  await compareFirstName(firstName: firstName)
  await uploadFirstName(firstName: firstName)
}

If it is crucial that they run on different priorities, you can do various things such as nesting tasks.

  • Related