'One method in many Tasks async/await

Hi I have a case where I need to call the same method in multiple Tasks. I want to have a possibility to call this method one by one (sync) not in parallel mode. It looks like that:

var isReadyToRefresh: Bool = true

func refresh(value: Int) async {
    try! await Task.sleep(nanoseconds: 100_000_000) // imitation API CALL
    isReadyToRefresh = false
    print("Try to refresh: \(value)")
}

func mockCallAPI(value: Int) async {
    if isReadyToRefresh {
        await refresh(value: value)
    }
}

Task {
     await mockCallAPI(value: 1)
}

Task {
     await mockCallAPI(value: 2)
}

output:

Try to refresh: 1

Try to refresh: 2

my required output:

Try to refresh: 1 OR Try to refresh 2. Depends which task has been called as first one.

Any ideas?



Solution 1:[1]

Why do they need to be in seperate tasks if you don't want them to run in parallel, await means the code will no progress any further than after the task completes, because of cooperative threading the thread that initiated it may be used to do something else, like process more using interaction, or other tasks, in fact because you have them in seperate task you are asking for them to be run in parallel, its possible the block that contains them will enter the very bringing and you will have another two task, in which case you need to wait on a result from them container task saying they have completed, and the code that entered the block checks this to continue any further.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nathan Day