Home > Back-end >  How to use Swift async/await in parallel
How to use Swift async/await in parallel

Time:10-08

Consider the code below:

class UserProfile
{
    private var img: UIImage? {
       didSet { /* update ui */ }
    }
    private var bio: String? {
       didSet { /* update ui */ }
    }

    private func loadImage() async -> UIImage? {
        // ... 
    }

    private func loadBio() async -> String? {
        // ...
    }

    public func loadData() async {
        async let img = loadImage()
        async let bio = loadBio()

        self.img = await img
        self.bio = await bio
    }
}

While this one does run the loading routines in parallel, assigning the results is synchronized: self.bio will always be assigned after self.img. This means the UI for the bio will have to wait for the image to be loaded. I would like these to be decoupled from each other. Completion handlers would have been ideal here, but we're using the async API. How do I make it so the assignment happens in the order of completion?

CodePudding user response:

you could try something like this:

func loadData() async {
    await withTaskGroup(of: Void.self) { group in
        group.addTask { self.img = await loadImage() }
        group.addTask { self.bio = await loadBio() }
    }
}

CodePudding user response:

I believe using tuples would solve this:

(self.img, self.bio) = await (img, bio)

  • Related