10

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?

2 Answers 2

20

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() }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

8

I believe using tuples would solve this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.