Skip to content

Instantly share code, notes, and snippets.

@takasurazeem
Last active December 7, 2024 11:54
Show Gist options
  • Save takasurazeem/8f78283553ea1b74424aa90f7b4b38dd to your computer and use it in GitHub Desktop.
Save takasurazeem/8f78283553ea1b74424aa90f7b4b38dd to your computer and use it in GitHub Desktop.
//
// ContentView.swift
// StateSample
//
// Created by Martin Poulsen on 2024-12-01.
//
import SwiftUI
// View protocol is on the @MainActor (and Maintread).
struct ContentView: View {
// A @State variable that holds the text displayed in the interface
@State private var text = "Waiting..."
var body: some View {
VStack(spacing: 20) {
Text(text)
.padding()
Button("Start Background Task") {
Task {
// After 'await', we continue on the MainActor (main thread), so updating 'text' is safe and keeps UI updates smooth. As HWS mentions, '@State' can be updated from any thread, but doing so on the MainActor is good practice.
text = await startBackgroundTask()
// Even though @State properties are thread-safe and can be updated from any thread (as per the HWS tip), updating them on the MainActor ensures that your UI remains responsive and free from threading issues.
}
}
}
}
// Call the nonisolated function on a background thread
// What nonisolated does is stop any actor inference and ensure that there will not be any isolation for a function. No isolation means no MainActor and that means background thread.
nonisolated func startBackgroundTask() async -> String {
// Simulate network delay
// You can set a breakpoint here, to check the tread
try? await Task.sleep(for: .seconds(2))
return "Updated from background task"
}
}
#Preview {
ContentView()
}
@takasurazeem
Copy link
Author

Context:

I am learning Swift concurrency in depth and I started with HWS's Swift Concurrency by Example
Under the topic: Understanding threads and queues it says:
Tip: Sometimes Apple’s frameworks will help you a little here. For example, even though using the @State property wrapper in a view will cause the body to be refreshed when the property is changed, this property wrapper is designed to be safe to call on any thread.
But there isn't any code example to better understand the sentence, if anyone familiar with the topic could share a code example that'd be very helpful, thank you.

https://hackingwithswift.slack.com/archives/C012XAR7XUM/p1733083379185269?thread_ts=1733058958.495059&cid=C012XAR7XUM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment