In SwiftUI, `task`, `onAppear`, and `onChange` modifiers allow you to perform side effects in your views such as fetching data or responding to state changes. Each method has its purpose and scope of execution.
The `task` modifier is used to run asynchronous tasks when a view appears. This is particularly useful for data-fetching operations that should start when the view is presented.
The `onAppear` modifier executes code every time the view appears. It's a great place to start animations or log data events.
The `onChange` modifier allows you to respond to specific state changes in your view. It's useful for executing logic when a value changes.
// Example of using task, onAppear, and onChange in SwiftUI
struct ContentView: View {
@State private var data: String = "Initial Data"
@State private var shouldFetchData: Bool = false
var body: some View {
Text(data)
.onAppear {
// Perform side effect: fetch initial data
loadData()
}
.onChange(of: shouldFetchData) { newValue in
// Perform side effect: fetch data when flag changes
if newValue {
loadData()
}
}
.task {
// Perform asynchronous side effect
await fetchData()
}
}
func loadData() {
data = "Data Loaded"
}
func fetchData() async {
// Simulate fetching data
await Task.sleep(2 * 1_000_000_000) // Sleep for 2 seconds
data = "Fetched Data"
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?