Skip to content

Instantly share code, notes, and snippets.

@2no
Created May 31, 2020 13:18
Show Gist options
  • Save 2no/175a6f405f26896a4a515bb59122baf6 to your computer and use it in GitHub Desktop.
Save 2no/175a6f405f26896a4a515bb59122baf6 to your computer and use it in GitHub Desktop.
SwiftUI+Alert Queue
import Combine
import SwiftUI
class AlertManager: ObservableObject {
@Published var isPresented = false
private var queues: [Alert] = []
private var cancellable: AnyCancellable?
init() {
cancellable = $isPresented
.filter({ [weak self] isPresented in
guard let self = self else {
return false
}
return !isPresented && !self.queues.isEmpty
})
.receive(on: DispatchQueue.main)
.sink(receiveValue: { [weak self] _ in
self?.isPresented = true
})
}
func enqueue(_ alert: Alert) {
queues.append(alert)
isPresented = true
}
func dequeue() -> Alert {
queues.removeFirst()
}
}
import SwiftUI
struct RootView: View {
@ObservedObject private var alertManager = AlertManager()
var body: some View {
Button(action: {
self.alertManager.enqueue(Alert(title: Text("test1")))
self.alertManager.enqueue(Alert(title: Text("test2")))
}) {
Text("test")
}
.alert(isPresented: $alertManager.isPresented) {
alertManager.dequeue()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment