-
-
Save js/de3b2ce690250caba432cc3437a63dab to your computer and use it in GitHub Desktop.
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 | |
final actor Worker: ObservableObject { | |
@MainActor @Published private(set) var lastWorkDoneAt: Date? | |
private var counter = 0 | |
func doWork() { | |
self.counter += 1 | |
DispatchQueue.main.async { | |
self.lastWorkDoneAt = .now | |
} | |
} | |
func fetchWorkCounter() -> Int { | |
return counter | |
} | |
} | |
struct MyTestView: View { | |
@StateObject private var worker = Worker() | |
@State private var queuedWorkCount: Int = 0 | |
@State private var fetchedWorkCount: Int = 0 | |
var body: some View { | |
let _ = Self._printChanges() | |
VStack { | |
Text("Queued Work Count: \(queuedWorkCount)") | |
Text("Fetched Work Count: \(fetchedWorkCount)") | |
Divider() | |
Button { | |
Task { | |
for i in 1...100 { | |
queuedWorkCount += 1 | |
await worker.doWork() | |
} | |
} | |
} label: { | |
Text("Enqueue 100 Work") | |
} | |
} | |
.onReceive(worker.lastWorkDoneAt.publisher, perform: { _ in | |
Task { | |
fetchedWorkCount = await worker.fetchWorkCounter() | |
} | |
}) | |
// .task(id: worker.lastWorkDoneAt) { | |
// fetchedWorkCount = await worker.fetchWorkCounter() | |
// } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment