Created
February 13, 2022 07:48
-
-
Save JadenGeller/c50be0a4e71a7c3102ccf7a37f9b8dac to your computer and use it in GitHub Desktop.
Render SwiftUI content view as a function of publisher's latest output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
AsyncSequence
variant: Latest