0

What would be the proper way to avoid Task {} inside a .onReceive() closure and still be able to run async code?

If I add a Task {} everything runs as it should but shouldn't I replace all Task {} blocks in swiftui? Whenever possible I'm using .task directly on the view but in this case I need to run an URLSession from a publisher onReceive closure.

2
  • Can you show a concrete example?
    – Sweeper
    Commented Sep 11, 2023 at 9:38
  • .onReceive updates @State var triggerFromPublisher and .task(id: triggerFromPublisher) will run any async code needed
    – pnbv
    Commented Sep 11, 2023 at 22:53

1 Answer 1

1

You can have the onReceive alter a variable that serves as an id for task.

struct TestURLSessionOnReceive: View {
    //Object from the publisher/task id
    @State private var id: UUID?
    //Result from async task
    @State private var progress: String?
    var body: some View {
        VStack{
            Button("post notification") { //Mocking a publisher trigger
                NotificationCenter.default.post(name: .someNotification, object: UUID.init().uuidString)
            }
            if let progress { //Mocking a result from an async task
                ProgressView {
                    Text(progress)
                }
            }
        }
        //Listen for the publisher
        .onReceive(NotificationCenter.default.publisher(for: .someNotification), perform: { notification in
            guard let uuidString = notification.object as? String, let uuid = UUID(uuidString: uuidString) else {
                return
            }
            self.id = uuid
        })
        //Complete a task based on a publisher
        .task(id: id) {
            guard let id else {return} //Ignore the "onAppear" call
            progress = "Working on\nid = \(id)"
            //Do any async await code
            
            //let (data, response) = try await URLSession.shared.data(from: <#T##URL#>)
            try? await Task.sleep(for: .seconds(2)) //Mocking async task
            
            progress = nil
        }
    }
}

extension Notification.Name {

    static let someNotification = Notification.Name("someNotification")
}
7
  • Thanks lorem ipsum! Should I also avoid having multiple .task{} definitions?
    – pnbv
    Commented Sep 11, 2023 at 22:57
  • @pnbv I don’t think there is a particular restriction Commented Sep 11, 2023 at 23:08
  • Nice! @loremipsum What about .onAppear { DispatchQueue.main.async {} } on ContentView type of patterns one sees a lot about, it seems I can replace this also with .task{}, is this a best practice when applied to window managing on (macOS) App launch?
    – pnbv
    Commented Sep 11, 2023 at 23:51
  • @pnbv I think with the new Concurrency that includes task and async/await there is no room for DispatchQueue or any of the GCD methods. The new Concurrency is the future, you can watch “Meet async/await” from WWDC it is a complete replacement. Commented Sep 11, 2023 at 23:58
  • you can remove the onReceive and just use for await _ in NotificationCenter.default.notifications(named:) directly from the .task.
    – malhal
    Commented Apr 6 at 17:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.