async button

By Brendan

Mahid has an interesting idea for an async button.

struct AsyncButton<Label: View>: View {
    let action: () async -> Void
    let label: Label

    @State private var isRunning = false

    init(
        action: @escaping () async -> Void,
        @ViewBuilder label: () -> Label
    ) {
        self.action = action
        self.label = label()
    }

    var body: some View {
        Button {
            isRunning = true
            Task {
                await action()
                isRunning = false
            }
        } label: {
            label
        }
        .disabled(isRunning)
    }
}

He even has a way to make the button cancellable … see his post for more details.