Use Combine for MongoController status changes

This commit is contained in:
Shadowfacts 2020-07-06 10:45:53 -04:00
parent bb695fbf53
commit 967a2518b4
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
2 changed files with 16 additions and 19 deletions

View File

@ -9,6 +9,7 @@
import Foundation
import MongoSwift
import NIO
import Combine
class MongoController {
let connectionString: String
@ -17,12 +18,7 @@ class MongoController {
var client: MongoClient!
var status: Status = .connecting {
didSet {
statusDidChange.forEach { $0(status) }
}
}
var statusDidChange = [(Status) -> Void]()
@Published var status: ConnectionStatus = .connecting
init(connectionString: String) {
self.connectionString = connectionString
@ -40,7 +36,7 @@ class MongoController {
do {
client = try MongoClient(connectionString, using: group)
status = .success
status = .connected
} catch {
status = .failed
print("Failed to connect to Mongo: \(error)")
@ -58,7 +54,7 @@ class MongoController {
}
extension MongoController {
enum Status {
case connecting, success, failed
enum ConnectionStatus {
case connecting, connected, failed
}
}

View File

@ -7,6 +7,7 @@
//
import Cocoa
import Combine
class DatabaseWindowController: NSWindowController {
@ -21,6 +22,8 @@ class DatabaseWindowController: NSWindowController {
private var databaseViewController: DatabaseViewController!
private var statusDidChangeHandler: Cancellable?
convenience init() {
self.init(windowNibName: "DatabaseWindowController")
}
@ -32,17 +35,15 @@ class DatabaseWindowController: NSWindowController {
if setupMongo {
mongoController = MongoController(connectionString: "mongodb://localhost:27017")
}
mongoController.statusDidChange.append({ [weak self] (status) in
guard let self = self else { return }
self.updateStatusText(status)
statusDidChangeHandler = mongoController.$status
.receive(on: DispatchQueue.main)
.sink { (status) in
self.updateStatusText(status)
if status == .success {
DispatchQueue.main.async {
if status == .connected {
self.initializeUI()
}
}
})
self.updateStatusText(mongoController.status)
if setupMongo {
mongoController.setup()
}
@ -65,14 +66,14 @@ class DatabaseWindowController: NSWindowController {
window?.title = databaseViewController?.title ?? "MongoView"
}
private func updateStatusText(_ status: MongoController.Status) {
private func updateStatusText(_ status: MongoController.ConnectionStatus) {
guard let statusView = self.statusView else { return }
switch status {
case .connecting:
statusView.setText("Connecting...")
case .failed:
statusView.setText("Failed to connect")
case .success:
case .connected:
statusView.setText("Connected to \(self.mongoController.connectionString)")
}
}