Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active July 13, 2022 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/5ab8c464958ccc46afe67271886b0aa9 to your computer and use it in GitHub Desktop.
Save JadenGeller/5ab8c464958ccc46afe67271886b0aa9 to your computer and use it in GitHub Desktop.
Latest
import SwiftUI
// WARNING: This probably won't work how you want it to. Task only runs once per view (based on identity), so changing the sequence doesn't update the latest value!
struct Latest<S: AsyncSequence, Content: View>: View {
var sequence: S
var content: (S.Element?, Error?) -> Content
init(_ sequence: S, @ViewBuilder content: @escaping (S.Element?, Error?) -> Content) {
self.sequence = sequence
self.content = content
}
@State var latest: S.Element?
@State var error: Error?
var body: some View {
content(latest, error)
.task {
do {
for try await element in sequence {
self.latest = element
}
} catch {
self.error = error
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment