Michael Long
Jul 15, 2024

--

If task only occurred once you'd have no need for the entire article.

Put some debug print statements in onAppear and task and put them in a master detail app where you leave the screen and return to it.

struct MainView3: View {

@StateObject var viewModel: ViewModel = .init()

var body: some View {

NavigationStack {

List {

ForEach(viewModel.characters) { item in

NavigationLink {

Text(item.name)

} label: {

MainItemView(item: item)

}

}

}

.task {

print("task")

}

.onAppear {

print("appear")

}

}

}

}

Both are fired when the view appears, and both are fired when you navigate to the detail screen and return.

onAppear, however, has less overhead than setting up an asynchronous context.

Run the code.

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

No responses yet