Last active
August 5, 2023 03:24
-
-
Save yimajo/8f7946cb273f58493a5cfaaecd770f3b to your computer and use it in GitHub Desktop.
Monitor FirebaseAuth login status with TCA
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 ComposableArchitecture | |
import FirebaseCore | |
import FirebaseAuth | |
import GoogleSignIn | |
struct FirebaseAuthClient { | |
var observeSignInState: () async -> AsyncStream<Bool> | |
} | |
extension FirebaseAuthClient { | |
static let liveValue = Self.live() | |
static func live() -> Self { | |
// To remove monitoring if called more than once. | |
var stateChangeListener: AuthStateDidChangeListenerHandle? | |
return Self(observeSignInState: { | |
if let stateChangeListener { | |
Auth.auth().removeStateDidChangeListener(stateChangeListener) | |
} | |
return AsyncStream(Bool.self) { continuation in | |
stateChangeListener = Auth.auth().addStateDidChangeListener { auth, _ in | |
continuation.yield(auth.currentUser != nil) | |
} | |
} | |
} | |
} | |
} | |
extension FirebaseAuthClient { | |
public static let noop = Self( | |
observeSignInState: { AsyncStream(Bool.self) { $0.finish() } } | |
) | |
} | |
// MARK: - For Dependencies | |
enum FirebaseAuthClientKey: DependencyKey { | |
static let liveValue = FirebaseAuthClient.liveValue | |
static let previewValue = FirebaseAuthClient.noop | |
} | |
extension DependencyValues { | |
var firebaseAuthClient: FirebaseAuthClient { | |
get { self[FirebaseAuthClientKey.self] } | |
set { self[FirebaseAuthClientKey.self] = newValue } | |
} | |
} |
Hi @andemengo . I am using this code from AppDelegate didFinishLaunching. isowords was used as a reference.
https://github.com/pointfreeco/isowords/blob/455238749625d8a84c23ee641d537971695416fc/App/iOS/App.swift#L39
Hi @andemengo . I am using this code from AppDelegate didFinishLaunching. isowords was used as a reference.
https://github.com/pointfreeco/isowords/blob/455238749625d8a84c23ee641d537971695416fc/App/iOS/App.swift#L39
That's perfect! Thanks also for the reference.
Just to be helpful at line 27
it's missing a the closing parentheses )
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @yimajo this is very interesting! How can we use this code in the concerned
ReducerProtocol
, and at the earliest possible moment (before even the.onAppear
)?