Skip to content

A SwiftUI view that performs an async task on appearing, allowing the caller to display different views for the success and failure cases.

Notifications You must be signed in to change notification settings

danielctull/AsyncView

Repository files navigation

AsyncView

Latest release Swift 5.5 Platforms: iOS, macOS, tvOS, watchOS

A SwiftUI view that performs an async task when appearing and allows the caller show different views based on the success and failure cases.

Usage

This can be used with an async function that fetches some data and decodes it into a model. In the following example, we display a list of posts when they are received or show the error message if the call to fetchPosts fails.

struct Post: Identifiable {
    let id: String
    let title: String
}

struct PostsView: View {

    private func fetchPosts() async throws -> [Post] {
        return [] // Actually implement network call!
    }

    var body: some View {
        AsyncView {
            try await fetchPosts()
        } initial: {
            ProgressView()
        } success: { posts in
            Success(posts: posts)
        } failure: { error in
            Failure(error: error)
        }
    }

    struct Success: View {
        let posts: [Post]
        var body: some View {
            List(posts) { post in
                Text(post.title)
            }
        }
    }

    struct Failure: View {
        let error: Error
        var body: some View {
            Text(error.localizedDescription)
        }
    }
}

About

A SwiftUI view that performs an async task on appearing, allowing the caller to display different views for the success and failure cases.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Languages