Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Add AsyncStream support for Firebase Auth#15362

Merged
peterfriese merged 11 commits into
mainfirebase/firebase-ios-sdk:mainfrom
peterfriese/asyncsequences/authfirebase/firebase-ios-sdk:peterfriese/asyncsequences/authCopy head branch name to clipboard
Mar 31, 2026
Merged

Add AsyncStream support for Firebase Auth#15362
peterfriese merged 11 commits into
mainfirebase/firebase-ios-sdk:mainfrom
peterfriese/asyncsequences/authfirebase/firebase-ios-sdk:peterfriese/asyncsequences/authCopy head branch name to clipboard

Conversation

@peterfriese

@peterfriese peterfriese commented Sep 28, 2025

Copy link
Copy Markdown
Contributor

Fix #15361

To better align the Firebase Auth SDK with modern Swift concurrency, this PR introduces AsyncStream-based APIs for observing authentication state and ID token changes.

Key Features & Benefits

  • Modern Concurrency: New authStateChanges and idTokenChanges properties on Auth return an AsyncStream<User?>, allowing developers to use for await loops to monitor authentication events, which is more idiomatic in modern Swift.
  • Improved Ergonomics: These new APIs provide a more intuitive and readable alternative to the traditional closure-based listeners (addStateDidChangeListener and addIDTokenDidChangeListener).
  • Resource Safety: The streams are designed to be safely cancelled, preventing potential resource leaks. This is validated by comprehensive unit tests.

Implementation Details

  • The new async properties are housed in a new FirebaseAuth/Sources/Auth+Async.swift file.
  • Unit tests have been added in FirebaseAuth/Tests/Unit/AuthAsyncTests.swift to cover sign-in, sign-out, token refresh, and stream cancellation scenarios.
  • The FirebaseAuth/CHANGELOG.md has been updated to reflect these new features.
  • The new APIs are documented with clear usage examples, following Apple's documentation best practices.

Example Usage

Monitoring Authentication State

func monitorAuthState() async {
  for await user in Auth.auth().authStateChanges {
    if let user = user {
      print("User signed in: \(user.uid)")
      // Update UI or perform actions for a signed-in user.
    } else {
      print("User signed out.")
      // Update UI or perform actions for a signed-out state.
    }
  }
}

Monitoring ID Token Changes

func monitorIDTokenState() async {
  for await user in Auth.auth().idTokenChanges {
    if let user = user {
      print("ID token changed for user: \(user.uid)")
      // The user's ID token has been refreshed.
      // You can get the new token by calling user.getIDToken()
      do {
        let token = try await user.getIDToken()
        print("New ID token: \(token)")
        // Send the new token to your backend server, etc.
      } catch {
        print("Error getting ID token: \(error)")
      }
    }
  }
}

@peterfriese peterfriese self-assigned this Sep 28, 2025
@peterfriese peterfriese linked an issue Sep 28, 2025 that may be closed by this pull request
Comment thread FirebaseAuth/Sources/Swift/Auth/Auth+Async.swift Outdated
@peterfriese
peterfriese marked this pull request as ready for review September 30, 2025 09:06
@ncooke3

ncooke3 commented Oct 2, 2025

Copy link
Copy Markdown
Member

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces AsyncStream-based APIs for observing authentication state and ID token changes, which is a great step towards modernizing the Firebase Auth SDK for Swift concurrency. The implementation is clean, well-documented, and includes a good set of unit tests.

My review includes a few suggestions to enhance the new APIs and tests:

  • Broadening the API availability to support older OS versions where Swift concurrency is available.
  • Improving the robustness of the unit tests by replacing Task.sleep with expectations.
  • Refactoring duplicated setup code in the tests to improve maintainability.

Comment thread FirebaseAuth/Sources/Swift/Auth/Auth+Async.swift Outdated
Comment thread FirebaseAuth/Tests/Unit/AuthStateChangesAsyncTests.swift
Comment thread FirebaseAuth/Tests/Unit/AuthStateChangesAsyncTests.swift Outdated
Comment thread FirebaseAuth/Tests/Unit/IdTokenChangesAsyncTests.swift Outdated
Comment thread FirebaseAuth/Sources/Swift/Auth/Auth+Async.swift Outdated
Comment thread FirebaseAuth/Sources/Swift/Auth/Auth+Async.swift Outdated
Comment thread FirebaseAuth/Sources/Swift/Auth/Auth+Async.swift Outdated
Comment thread FirebaseAuth/Tests/Unit/IdTokenChangesAsyncTests.swift
Comment thread FirebaseAuth/Tests/Unit/IdTokenChangesAsyncTests.swift Outdated
Comment thread FirebaseAuth/Tests/Unit/IdTokenChangesAsyncTests.swift Outdated
Comment thread FirebaseAuth/Tests/Unit/IdTokenChangesAsyncTests.swift Outdated
Comment thread FirebaseAuth/Tests/Unit/AuthStateChangesAsyncTests.swift Outdated
Comment thread FirebaseAuth/Tests/Unit/AuthStateChangesAsyncTests.swift
Comment thread FirebaseAuth/Tests/Unit/AuthStateChangesAsyncTests.swift
@ncooke3 ncooke3 added the needs-jules-review Label for manually marking PRs as ready for a review from Jules. label Jan 28, 2026
@peterfriese
peterfriese force-pushed the peterfriese/asyncsequences/auth branch from 3b1b8d4 to 35f2754 Compare March 30, 2026 11:04
@peterfriese
peterfriese requested a review from ncooke3 March 30, 2026 13:08
peterfriese added a commit that referenced this pull request Mar 31, 2026
Introduces `AsyncSequence` support for `Query.snapshots` and `DocumentReference.snapshots`, 
enabling developers to handle Firestore real-time updates using Swift's structured 
concurrency.

- Provides a modern, async-await compatible alternative to `addSnapshotListener`.
- Supports both `Query` and `DocumentReference` snapshot streams.
- Automatically handles listener registration and cleanup on task cancellation.
- Configured with an unbounded buffering policy to ensure no snapshot events are lost.

This work follows similar patterns introduced for Firebase Auth and Remote Config, 
bringing consistency to the developer experience across the Firebase Apple SDKs.

Related Projects:
- Firebase Auth AsyncSequence (#15362)
- Remote Config AsyncSequence (#15352)

Public API:
- `DocumentReference.snapshots(includeMetadataChanges:) -> DocumentSnapshotsSequence`
- `Query.snapshots(includeMetadataChanges:) -> QuerySnapshotsSequence`

Tested on iOS, macOS, tvOS, and watchOS.

Signed-off-by: Peter Friese <peter@peterfriese.dev>
Co-authored-by: Nick Cooke <36927374+ncooke3@users.noreply.github.com>
This commit introduces an `AsyncStream`-based API for observing authentication state changes, aligning the Firebase Auth SDK with modern Swift concurrency patterns.

The new `authStateChanges` computed property on `Auth` returns an `AsyncStream<User?>` that emits the current user whenever the authentication state changes. This provides a more ergonomic alternative to the traditional closure-based `addStateDidChangeListener`.

Key changes include:
- The implementation of `authStateChanges` in a new `Auth+Async.swift` file.
-  Comprehensive unit tests in `AuthAsyncTests.swift` covering the stream's behavior for sign-in, sign-out, and cancellation scenarios to prevent resource leaks.
- An entry in the `FirebaseAuth/CHANGELOG.md` for the new feature.
- Detailed API documentation for `authStateChanges`, including a clear usage example, following Apple's documentation best practices.
This commit introduces an `AsyncStream`-based API for observing ID token changes, aligning the Firebase Auth SDK with modern Swift concurrency patterns.

The new `idTokenChanges` computed property on `Auth` returns an `AsyncStream<User?>` that emits the current user whenever the ID token changes. This provides a more ergonomic alternative to the traditional closure-based `addIDTokenDidChangeListener`.

Key changes include:
- The implementation of `idTokenChanges` in `Auth+Async.swift`.
- Comprehensive unit tests in `IdTokenChangesAsyncTests.swift` covering the stream's behavior.
- Renamed `AuthAsyncTests.swift` to `AuthStateChangesAsyncTests.swift` to better reflect its content.
@peterfriese
peterfriese force-pushed the peterfriese/asyncsequences/auth branch from 35f2754 to d26c0fa Compare March 31, 2026 11:10
Comment thread FirebaseAuth/Sources/Swift/Auth/Auth+Async.swift
Comment thread FirebaseAuth/Sources/Swift/Auth/Auth+Async.swift
@peterfriese
peterfriese merged commit 14c65ef into main Mar 31, 2026
80 checks passed
@peterfriese
peterfriese deleted the peterfriese/asyncsequences/auth branch March 31, 2026 16:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: auth needs-jules-review Label for manually marking PRs as ready for a review from Jules.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement AsyncStream support for Firebase Auth

3 participants

Morty Proxy This is a proxified and sanitized view of the page, visit original site.