2023-07-14 14:45:25 -07:00
|
|
|
//
|
2023-08-24 14:18:04 -07:00
|
|
|
// Copyright RevenueCat Inc. All Rights Reserved.
|
|
|
|
|
//
|
|
|
|
|
// Licensed under the MIT License (the "License");
|
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
|
//
|
|
|
|
|
// https://opensource.org/licenses/MIT
|
|
|
|
|
//
|
|
|
|
|
|
2023-07-14 14:45:25 -07:00
|
|
|
// AsyncButton.swift
|
|
|
|
|
//
|
|
|
|
|
// Created by Nacho Soto on 7/13/23.
|
|
|
|
|
|
|
|
|
|
import RevenueCat
|
|
|
|
|
import SwiftUI
|
|
|
|
|
|
2023-11-08 07:35:19 -08:00
|
|
|
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
|
2023-07-14 14:45:25 -07:00
|
|
|
struct AsyncButton<Label>: View where Label: View {
|
|
|
|
|
|
2023-07-21 06:51:31 +02:00
|
|
|
typealias Action = @Sendable @MainActor () async throws -> Void
|
2023-07-14 14:45:25 -07:00
|
|
|
|
|
|
|
|
private let action: Action
|
|
|
|
|
private let label: Label
|
|
|
|
|
|
|
|
|
|
@State
|
2023-07-24 15:49:26 +02:00
|
|
|
private var error: NSError?
|
2023-07-14 14:45:25 -07:00
|
|
|
|
2023-07-31 12:02:30 +02:00
|
|
|
init(
|
|
|
|
|
action: @escaping Action,
|
|
|
|
|
@ViewBuilder label: () -> Label
|
|
|
|
|
) {
|
2023-07-14 14:45:25 -07:00
|
|
|
self.action = action
|
|
|
|
|
self.label = label()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var body: some View {
|
|
|
|
|
Button {
|
|
|
|
|
Task<Void, Never> {
|
|
|
|
|
do {
|
|
|
|
|
try await self.action()
|
|
|
|
|
} catch let error as NSError {
|
2023-07-24 15:49:26 +02:00
|
|
|
self.error = error
|
2023-07-14 14:45:25 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} label: {
|
|
|
|
|
self.label
|
|
|
|
|
}
|
2023-07-24 15:49:26 +02:00
|
|
|
.displayError(self.$error)
|
2023-07-14 14:45:25 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|