Last active
February 28, 2020 18:20
-
-
Save damirstuhec/19d7f7b393a0f35a146bbd5fc710b836 to your computer and use it in GitHub Desktop.
SwiftUI Alert with Publisher
This file contains hidden or 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 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