Skip to content

Instantly share code, notes, and snippets.

@manmal
Last active June 11, 2021 15:32
Show Gist options
  • Save manmal/69b0a5275a98f6cccba1716015a7c2a5 to your computer and use it in GitHub Desktop.
Save manmal/69b0a5275a98f6cccba1716015a7c2a5 to your computer and use it in GitHub Desktop.
Async ObservableObject
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