-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncButtonExecution.swift
More file actions
49 lines (39 loc) · 1.34 KB
/
Copy pathAsyncButtonExecution.swift
File metadata and controls
49 lines (39 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
// AsyncButtonExecution.swift
// CustomComponents
//
// Created by Valeriy Malishevskyi on 13.05.2025.
//
import SwiftUI
@MainActor final class AsyncButtonExecution: ObservableObject {
@Published private(set) var task: Task<Void, Error>?
@Published private(set) var isLoading = false
private var options: AsyncButtonOptions = []
func start(options: AsyncButtonOptions, _ action: @escaping () async -> Void) {
self.options = options
self.task?.cancel()
self.task = Task { [weak self] in
let loadingIndicatorTask = Task {
try await Task.sleep(for: .seconds(1))
try Task.checkCancellation()
if !options.contains(.loadingIndicatorHidden) {
self?.isLoading = true
}
}
await action()
try Task.checkCancellation()
// Cancel loading indicator task
loadingIndicatorTask.cancel()
if !options.contains(.loadingIndicatorHidden) {
self?.isLoading = false
}
self?.task = nil
}
}
deinit {
MainActor.assumeIsolated {
guard !options.contains(.detachesTask) else { return }
task?.cancel()
}
}
}