Skip to content

Instantly share code, notes, and snippets.

@SwiftyAlex
Created June 7, 2021 22:14
Show Gist options
  • Save SwiftyAlex/917d93329da18c1cbf3f3cf08d7801a1 to your computer and use it in GitHub Desktop.
Save SwiftyAlex/917d93329da18c1cbf3f3cf08d7801a1 to your computer and use it in GitHub Desktop.
Async brew fetching.
struct Coffee: Hashable {
let name: String
}
class CoffeeStore: ObservableObject {
func getCoffee() async -> [Coffee] {
Thread.sleep(forTimeInterval: 2)
return [
Coffee(name: "Cortado"),
Coffee(name: "Flat White")
]
}
}
struct ContentView: View {
@StateObject var coffeeStore = CoffeeStore()
@State var coffees: [Coffee] = []
var body: some View {
List {
if coffees.isEmpty {
ProgressView()
.progressViewStyle(CircularProgressViewStyle())
.frame(maxWidth: .infinity, alignment: .center)
} else {
Section("Coffees") {
ForEach(coffees, id: \.self) { coffee in
Text(coffee.name)
.font(.headline)
}
}
}
}
.onAppear {
loadContent()
}
}
private func loadContent() {
async {
let coffee = await coffeeStore.getCoffee()
self.coffees = coffee
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment