Skip to content

Commit 8278f04

Browse files
chore: auth listener manager to enable removal of listener
1 parent 393c238 commit 8278f04

1 file changed

Lines changed: 29 additions & 23 deletions

File tree

FirebaseSwiftUI/FirebaseAuthSwiftUI/Sources/FirebaseAuthSwiftUI/Services/AuthEnvironment.swift

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,32 @@ public enum AuthenticationFlow {
2323
case signUp
2424
}
2525

26+
@MainActor
27+
final class AuthListenerManager {
28+
private var authStateHandle: AuthStateDidChangeListenerHandle?
29+
private let auth: Auth
30+
private weak var authEnvironment: AuthEnvironment?
31+
32+
init(auth: Auth, authEnvironment: AuthEnvironment) {
33+
self.auth = auth
34+
self.authEnvironment = authEnvironment
35+
setupAuthenticationListener()
36+
}
37+
38+
deinit {
39+
if let handle = authStateHandle {
40+
auth.removeStateDidChangeListener(handle)
41+
}
42+
}
43+
44+
private func setupAuthenticationListener() {
45+
authStateHandle = auth.addStateDidChangeListener { [weak self] _, user in
46+
self?.authEnvironment?.currentUser = user
47+
self?.authEnvironment?.updateAuthenticationState()
48+
}
49+
}
50+
}
51+
2652
@MainActor
2753
@Observable
2854
public final class AuthEnvironment {
@@ -36,35 +62,15 @@ public final class AuthEnvironment {
3662
var currentUser: User?
3763
var errorMessage = ""
3864

39-
private init() {
40-
setupAuthenticationListener()
41-
}
65+
private var listenerManager: AuthListenerManager?
4266

43-
deinit {
44-
if let handle = authStateHandle {
45-
auth.removeStateDidChangeListener(handle)
46-
authStateHandle = nil
47-
}
67+
private init() {
68+
listenerManager = AuthListenerManager(auth: auth, authEnvironment: self)
4869
}
4970

5071
public var authenticationState: AuthenticationState = .unauthenticated
5172
public var authenticationFlow: AuthenticationFlow = .login
5273

53-
private func setupAuthenticationListener() {
54-
authStateHandle = auth.addStateDidChangeListener { [weak self] _, user in
55-
self?.currentUser = user
56-
self?.updateAuthenticationState()
57-
}
58-
}
59-
60-
private nonisolated(unsafe) var authStateHandle: AuthStateDidChangeListenerHandle? {
61-
willSet {
62-
if let handle = authStateHandle {
63-
auth.removeStateDidChangeListener(handle)
64-
}
65-
}
66-
}
67-
6874
func updateAuthenticationState() {
6975
authenticationState =
7076
(currentUser == nil || currentUser?.isAnonymous == true)

0 commit comments

Comments
 (0)