Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Last active June 3, 2025 18:48
Show Gist options
  • Save hmlongco/c296911b56bf6c79dd8d169bc45da1e5 to your computer and use it in GitHub Desktop.
Save hmlongco/c296911b56bf6c79dd8d169bc45da1e5 to your computer and use it in GitHub Desktop.
// demonstrate advantages of moving task from view to loading state
struct FeedView: View {
@Environment(BlueSkyClient.self) private var client
@Environment(AppTheme.self) private var theme
enum ViewState {
case loading
case error(String)
case loaded([Post])
}
@State private var viewState: ViewState = .loading
var body: some View {
NavigationStack {
List {
switch viewState {
case .loading:
ProgressView("Loading feed...")
.frame(maxWidth: .infinity)
.listRowSeparator(.hidden)
.task { await loadFeed() } // move task here
case .error(let message):
ErrorStateView(
message: message,
retryAction: { viewState = .loading } // just reset state
)
.listRowSeparator(.hidden)
case .loaded(let posts):
ForEach(posts) { post in
PostRowView(post: post)
.listRowInsets(.init())
}
}
}
.listStyle(.plain)
.refreshable { viewState = .loading } // just reset state
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment