Skip to content

Commit

Permalink
Simplify notification observer using init/deinit
Browse files Browse the repository at this point in the history
  • Loading branch information
tadaskay committed Jan 19, 2024
1 parent e80dbb9 commit 3ac0140
Showing 1 changed file with 18 additions and 21 deletions.
39 changes: 18 additions & 21 deletions darwin/Classes/ConnectionStatusObserver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,53 +2,50 @@
import Flutter
import UIKit
#elseif os(macOS)
import FlutterMacOS
import Cocoa
import FlutterMacOS
#else
#error("Unsupported platform")
#endif

import NetworkExtension
import WireGuardKit
import os
import WireGuardKit

class ConnectionStatusObserver: NSObject, FlutterStreamHandler {

private var eventSink: FlutterEventSink?
private var isRunning: Bool = false

override init() {
super.init()
NotificationCenter.default.addObserver(
forName: NSNotification.Name.NEVPNStatusDidChange,
object: nil,
queue: OperationQueue.main,
using: handleStatusChanged
)
}

deinit {
NotificationCenter.default.removeObserver(self)
}

public func handleStatusChanged(notification: Notification?) {
guard let conn = notification?.object as? NEVPNConnection else {
return
}
guard let eventSink = eventSink else {
return
}
let newStatus = ConnectionStatus.fromNEVPNStatus(status: conn.status)

Logger.main.debug("VPN status changed: \(newStatus.string())")
eventSink(newStatus.string())
eventSink?(newStatus.string())
}

public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
self.eventSink = events

if !isRunning {
NotificationCenter.default.addObserver(
forName: NSNotification.Name.NEVPNStatusDidChange,
object: nil,
queue: OperationQueue.main,
using: handleStatusChanged
)
}

isRunning = true
eventSink = events
return nil
}

public func onCancel(withArguments arguments: Any?) -> FlutterError? {
isRunning = false
NotificationCenter.default.removeObserver(self)
eventSink = nil
return nil
}
Expand Down

0 comments on commit 3ac0140

Please sign in to comment.