Last active
June 11, 2021 15:32
-
-
Save manmal/69b0a5275a98f6cccba1716015a7c2a5 to your computer and use it in GitHub Desktop.
Async ObservableObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
@MainActor | |
class PhotoStore: ObservableObject { | |
@Published private(set) var isSaving: Bool = false | |
// Made nonisolated because Playgrounds does not run on | |
// @MainActor. There's probably a cleaner way of doing this | |
nonisolated init() {} | |
func savePhoto(_ photo: Any) async -> Bool { | |
isSaving = true | |
await withUnsafeContinuation { c in | |
DispatchQueue.global().asyncAfter(deadline: .now() + 1) { | |
c.resume() | |
} | |
} | |
isSaving = false | |
return true | |
} | |
} | |
struct AsyncObservableRootView: View { | |
@StateObject var store: PhotoStore | |
var body: some View { | |
SavePhotoButton(photo: (), store: store) | |
} | |
} | |
struct SavePhotoButton: View { | |
var photo: Any | |
@ObservedObject private(set) var store: PhotoStore | |
var body: some View { | |
Button { | |
async { | |
await store.savePhoto(()) | |
} | |
} label: { | |
Text("Save") | |
.opacity(store.isSaving ? 0 : 1) | |
.overlay { | |
if store.isSaving { | |
ProgressView() | |
} | |
} | |
} | |
.disabled(store.isSaving) | |
.buttonStyle(.bordered) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment