PublisherView

main

A SwiftUI view that subscribes to a Combine publisher to display different views for the values and failure of the publisher.
danielctull/PublisherView

PublisherView

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

A SwiftUI view that subscribes to a Combine publisher to show different views for values and failures.

Usage

This can be used with a data task publisher which then decodes the data into model objects. In this example We display a list of posts when they are received or show the error message on screen if the task fails.

struct PostsView: View {
  // Get this publisher from somewhere, maybe a data task publisher
  let publisher: AnyPublisher<[Post], Error>
  var body: some View {
    PublisherView(publisher: publisher,
                  initial: LoadingView.init,
                  output: Content.init,
                  failure: FailureView.init)
  }
}

extension PostsView {

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

struct LoadingView: View {
  var body: some View {
    // Some awesome loading view
  }
}

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

Description

  • Swift Tools 5.1.0
View More Packages from this Author

Dependencies

  • None
Last updated: Mon Oct 21 2024 19:58:53 GMT-0900 (Hawaii-Aleutian Daylight Time)