Skip to content

AsyncViewBuilders

Nick Sarno edited this page Jan 13, 2024 · 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 specify the Task's priority and redacted style. Only the loading phase will be redacted.

AsyncViewBuilder(priority: .medium, redactedStyle: .placeholder) {
     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(let error):
            Text(error.localizedDescription)
     }
}

Set redactedOnFailure to true to keep the View redacted on .failure.

AsyncViewBuilder(redactedStyle: .placeholder, redactedOnFailure: true) {
     try await fetchImage()
} content: { phase in
     switch phase {
     case .loading, .failure:
          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)
     }
}

AsyncLetViewBuilder

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

AsyncLetViewBuilder(redactedStyle: .opacity) {
     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