Skip to content

Instantly share code, notes, and snippets.

@yimajo
Last active August 5, 2023 03:24
Show Gist options
  • Save yimajo/8f7946cb273f58493a5cfaaecd770f3b to your computer and use it in GitHub Desktop.
Save yimajo/8f7946cb273f58493a5cfaaecd770f3b to your computer and use it in GitHub Desktop.
Monitor FirebaseAuth login status with TCA
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 }
}
}
@andemengo
Copy link

andemengo commented Mar 12, 2023

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