Skip to content

Instantly share code, notes, and snippets.

@damirstuhec
Last active February 28, 2020 18:20
Show Gist options
  • Save damirstuhec/19d7f7b393a0f35a146bbd5fc710b836 to your computer and use it in GitHub Desktop.
Save damirstuhec/19d7f7b393a0f35a146bbd5fc710b836 to your computer and use it in GitHub Desktop.
SwiftUI Alert with Publisher
import SwiftUI
import Combine
struct AlertWithPublisher<P>: ViewModifier where P: Publisher, P.Failure == Never {
let publisher: P
let alertContent: (P.Output?) -> Alert
@State private var isShowingAlert = false
@State private var publisherOutput: P.Output? = nil
func body(content: Content) -> some View {
content
.alert(isPresented: self.$isShowingAlert) {
self.alertContent(self.publisherOutput)
}
.onReceive(publisher) { output in
self.publisherOutput = output
self.isShowingAlert.toggle()
}
}
}
extension View {
func alert<P>(onReceive publisher: P, content: @escaping (P.Output?) -> Alert) -> some View where P: Publisher, P.Failure == Never {
modifier(AlertWithPublisher(publisher: publisher, alertContent: content))
}
}
/* Usage
.alert(onReceive: publisher) { output in
Alert(title: Text("Alert"), message: Text("Presented from publisher."), dismissButton: .cancel())
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment