Created
May 31, 2020 13:18
-
-
Save 2no/175a6f405f26896a4a515bb59122baf6 to your computer and use it in GitHub Desktop.
SwiftUI+Alert Queue
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 | |
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() | |
} | |
} |
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 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