Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created February 13, 2022 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/c50be0a4e71a7c3102ccf7a37f9b8dac to your computer and use it in GitHub Desktop.
Save JadenGeller/c50be0a4e71a7c3102ccf7a37f9b8dac to your computer and use it in GitHub Desktop.
Render SwiftUI content view as a function of publisher's latest output
import Combine
import SwiftUI
struct SubscriberView<Publisher: Combine.Publisher, Content: View>: View where Publisher.Failure == Never {
let publisher: Publishers.Share<Publisher>
let content: (Publisher.Output?) -> Content
init(_ publisher: Publisher, @ViewBuilder content: @escaping (Publisher.Output?) -> Content) {
// Apply `share` in `init` to prevent recreating the subscription from scratch when `latest` is set.
self.publisher = publisher.share()
self.content = content
}
@State var latest: Publisher.Output? = nil
var body: some View {
content(latest)
.onReceive(publisher.receive(on: RunLoop.main)) { next in
self.latest = next
}
}
}
@JadenGeller
Copy link
Author

JadenGeller commented Jul 12, 2022

AsyncSequence variant: Latest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment