Skip to content

AsyncViewBuilders

Nick Sarno edited this page Apr 3, 2022 · 6 revisions

AsyncViewBuilder

Load any View from an asynchronous method and easily manage loading states.

AsyncViewBuilder {
     try await fetchImage()
} content: { phase in
     switch phase {
     case .loading:
          ProgressView()
     case .success(let image):
          Image(uiImage: image)
     case .failure:
          Text("Error")
     }
}

Optionally add a redacted state during the .loading phase or specify the Task's priority.

AsyncViewBuilder(redactedStyle: .placeholder, priority: .medium) {
     try await fetchImage()
} content: { phase in
     switch phase {
     case .loading:
          Image(uiImage: UIImage(systemName: "heart.fill")!)
               .resizable()
               .scaledToFit()
               .frame(width: 200, height: 200)
     case .success(let image):
           Image(uiImage: image)
               .resizable()
               .scaledToFit()
               .frame(width: 200, height: 200)
     case .failure:
            Text("Error")
     }
}

AsyncLetViewBuilder

Use the async let version when loading from two asynchronous methods concurrently.

AsyncLetViewBuilder(redactedStyle: .opacity, priority: .low) {
     try await fetchImage()
} fetchB: {
     try await fetchText()
} content: { phase in
     switch phase {
     case .loading:
          ProgressView()
     case .success(valueA: let image, valueB: let text):
          HStack {
               Image(uiImage: image)
               Text(text)
          }
     case .failure:
          Text("Error")
     }
}
Clone this wiki locally