- 
                Notifications
    
You must be signed in to change notification settings  - Fork 1.7k
 
Add AsyncStream support for Firebase Auth #15362
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            peterfriese
  wants to merge
  8
  commits into
  main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
peterfriese/asyncsequences/auth
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
      
        
          +611
        
        
          −0
        
        
          
        
      
    
  
  
     Open
                    Changes from 6 commits
      Commits
    
    
            Show all changes
          
          
            8 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      1b0c295
              
                Add `authStateChanges` async stream to `Auth`
              
              
                peterfriese 69d2f30
              
                Add `idTokenChanges` async stream to `Auth`
              
              
                peterfriese f8f9386
              
                Remove explicit return statements
              
              
                peterfriese ac13e18
              
                Update changelog
              
              
                peterfriese 3fe6416
              
                Return stream as a sequence
              
              
                peterfriese 60c2432
              
                Fix formatting
              
              
                peterfriese 62742e9
              
                Address feedback from review
              
              
                peterfriese 46a525d
              
                Make sure the AsyncSequences returned from authStateChanges and idTok…
              
              
                peterfriese File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or 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
    
  
  
    
              
              
  
    
      This file contains hidden or 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
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| // Copyright 2025 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| 
     | 
||
| import Foundation | ||
| 
     | 
||
| public extension Auth { | ||
| /// An asynchronous sequence of authentication state changes. | ||
| /// | ||
| /// This sequence provides a modern, `async/await`-compatible way to monitor the authentication | ||
| /// state of the current user. It emits a new `User?` value whenever the user signs in or | ||
| /// out. | ||
| /// | ||
| /// The sequence's underlying listener is automatically managed. It is added to the `Auth` | ||
| /// instance when you begin iterating over the sequence and is removed when the iteration | ||
| /// is cancelled or terminates. | ||
| /// | ||
| /// - Important: The first value emitted by this sequence is always the *current* authentication | ||
| /// state, which may be `nil` if no user is signed in. | ||
| /// | ||
| /// ### Example Usage | ||
| /// | ||
| /// You can use a `for await` loop to handle authentication changes: | ||
| /// | ||
| /// ```swift | ||
| /// 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. | ||
| /// } | ||
| /// } | ||
| /// } | ||
| /// ``` | ||
| @available(iOS 18.0, *) | ||
| var authStateChanges: some AsyncSequence<User?, Never> { | ||
                
      
                  peterfriese marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| AsyncStream { continuation in | ||
| let listenerHandle = addStateDidChangeListener { _, user in | ||
| continuation.yield(user) | ||
| } | ||
| 
     | 
||
| continuation.onTermination = { @Sendable _ in | ||
| self.removeStateDidChangeListener(listenerHandle) | ||
| } | ||
| } | ||
| } | ||
| 
     | 
||
| /// An asynchronous sequence of ID token changes. | ||
| /// | ||
| /// This sequence provides a modern, `async/await`-compatible way to monitor changes to the | ||
| /// current user's ID token. It emits a new `User?` value whenever the ID token changes. | ||
| /// | ||
| /// The sequence's underlying listener is automatically managed. It is added to the `Auth` | ||
| /// instance when you begin iterating over the sequence and is removed when the iteration | ||
| /// is cancelled or terminates. | ||
| /// | ||
| /// - Important: The first value emitted by this sequence is always the *current* authentication | ||
| /// state, which may be `nil` if no user is signed in. | ||
| /// | ||
| /// ### Example Usage | ||
| /// | ||
| /// You can use a `for await` loop to handle ID token changes: | ||
| /// | ||
| /// ```swift | ||
| /// func monitorIDTokenChanges() async { | ||
| /// for await user in Auth.auth().idTokenChanges { | ||
| /// if let user = user { | ||
| /// print("ID token changed for user: \(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. | ||
| /// } | ||
| /// } | ||
| /// } | ||
| /// ``` | ||
| @available(iOS 18.0, *) | ||
| var idTokenChanges: some AsyncSequence<User?, Never> { | ||
| AsyncStream { continuation in | ||
| let listenerHandle = addIDTokenDidChangeListener { _, user in | ||
| continuation.yield(user) | ||
| } | ||
| 
     | 
||
| continuation.onTermination = { @Sendable _ in | ||
| self.removeIDTokenDidChangeListener(listenerHandle) | ||
| } | ||
| } | ||
| } | ||
| } | ||
        
          
          
            199 changes: 199 additions & 0 deletions
          
          199 
        
  FirebaseAuth/Tests/Unit/AuthStateChangesAsyncTests.swift
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or 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
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,199 @@ | ||
| // Copyright 2025 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
| 
     | 
||
| @testable import FirebaseAuth | ||
| import FirebaseCore | ||
                
      
                  peterfriese marked this conversation as resolved.
               
          
            Show resolved
            Hide resolved
         | 
||
| import XCTest | ||
| 
     | 
||
| @available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, watchOS 7.0, *) | ||
| class AuthStateChangesAsyncTests: RPCBaseTests { | ||
| var auth: Auth! | ||
| static var testNum = 0 | ||
                
      
                  peterfriese marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| 
     | 
||
| override func setUp() { | ||
| super.setUp() | ||
| let options = FirebaseOptions(googleAppID: "0:0000000000000:ios:0000000000000000", | ||
| gcmSenderID: "00000000000000000-00000000000-000000000") | ||
| options.apiKey = "FAKE_API_KEY" | ||
| options.projectID = "myProjectID" | ||
| let name = "test-AuthStateChangesAsyncTests\(AuthStateChangesAsyncTests.testNum)" | ||
| AuthStateChangesAsyncTests.testNum += 1 | ||
                
      
                  peterfriese marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| 
     | 
||
| FirebaseApp.configure(name: name, options: options) | ||
| let app = FirebaseApp.app(name: name)! | ||
| 
     | 
||
| #if (os(macOS) && !FIREBASE_AUTH_TESTING_USE_MACOS_KEYCHAIN) || SWIFT_PACKAGE | ||
| let keychainStorageProvider = FakeAuthKeychainStorage() | ||
| #else | ||
| let keychainStorageProvider = AuthKeychainStorageReal.shared | ||
| #endif | ||
| 
     | 
||
| auth = Auth( | ||
| app: app, | ||
| keychainStorageProvider: keychainStorageProvider, | ||
| backend: authBackend | ||
| ) | ||
| 
     | 
||
| waitForAuthGlobalWorkQueueDrain() | ||
| } | ||
                
      
                  peterfriese marked this conversation as resolved.
               
          
            Show resolved
            Hide resolved
         | 
||
| 
     | 
||
| override func tearDown() { | ||
| auth = nil | ||
| FirebaseApp.resetApps() | ||
| super.tearDown() | ||
| } | ||
| 
     | 
||
| private func waitForAuthGlobalWorkQueueDrain() { | ||
| let workerSemaphore = DispatchSemaphore(value: 0) | ||
| kAuthGlobalWorkQueue.async { | ||
| workerSemaphore.signal() | ||
| } | ||
| _ = workerSemaphore.wait(timeout: DispatchTime.distantFuture) | ||
                
      
                  peterfriese marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| } | ||
| 
     | 
||
| @available(iOS 18.0, *) | ||
| func testAuthStateChangesStreamYieldsUserOnSignIn() async throws { | ||
| // Given | ||
| let initialNilExpectation = expectation(description: "Stream should emit initial nil user") | ||
| let signInExpectation = expectation(description: "Stream should emit signed-in user") | ||
| try? auth.signOut() | ||
| 
     | 
||
| var iteration = 0 | ||
| let task = Task { | ||
| for await user in auth.authStateChanges { | ||
| if iteration == 0 { | ||
| XCTAssertNil(user, "The initial user should be nil") | ||
| initialNilExpectation.fulfill() | ||
| } else if iteration == 1 { | ||
| XCTAssertNotNil(user, "The stream should yield the new user") | ||
| XCTAssertEqual(user?.uid, kLocalID) | ||
| signInExpectation.fulfill() | ||
| } | ||
| iteration += 1 | ||
| } | ||
| } | ||
| 
     | 
||
| // Wait for the initial nil value to be emitted before proceeding. | ||
| await fulfillment(of: [initialNilExpectation], timeout: 1.0) | ||
| 
     | 
||
| // When | ||
| // A user is signed in. | ||
| setFakeGetAccountProviderAnonymous() | ||
| setFakeSecureTokenService() | ||
| rpcIssuer.respondBlock = { | ||
| try self.rpcIssuer.respond(withJSON: ["idToken": "TEST_ACCESS_TOKEN", | ||
| "refreshToken": self.kRefreshToken, | ||
| "isNewUser": true]) | ||
| } | ||
| _ = try await auth.signInAnonymously() | ||
| 
     | 
||
| // Then | ||
| // The stream should emit the new, signed-in user. | ||
| await fulfillment(of: [signInExpectation], timeout: 2.0) | ||
| task.cancel() | ||
| } | ||
| 
     | 
||
| @available(iOS 18.0, *) | ||
| func testAuthStateChangesStreamIsCancelled() async throws { | ||
| // Given: An inverted expectation that will fail the test if it's fulfilled. | ||
| let streamCancelledExpectation = | ||
| expectation(description: "Stream should not emit a value after cancellation") | ||
| streamCancelledExpectation.isInverted = true | ||
| try? auth.signOut() | ||
| 
     | 
||
| var iteration = 0 | ||
| let task = Task { | ||
| for await _ in auth.authStateChanges { | ||
| if iteration > 0 { | ||
| // This line should not be reached. If it is, the inverted expectation will be | ||
| // fulfilled, and the test will fail as intended. | ||
| streamCancelledExpectation.fulfill() | ||
| } | ||
| iteration += 1 | ||
| } | ||
| } | ||
| 
     | 
||
| // Let the stream emit its initial `nil` value. | ||
| try await Task.sleep(nanoseconds: 200_000_000) | ||
                
      
                  peterfriese marked this conversation as resolved.
               
              
                Outdated
          
            Show resolved
            Hide resolved
         | 
||
| 
     | 
||
| // When: The listening task is cancelled. | ||
| task.cancel() | ||
| 
     | 
||
| // And an attempt is made to trigger another update. | ||
| setFakeGetAccountProviderAnonymous() | ||
| setFakeSecureTokenService() | ||
| rpcIssuer.respondBlock = { | ||
| try self.rpcIssuer.respond(withJSON: ["idToken": "TEST_ACCESS_TOKEN", | ||
| "refreshToken": self.kRefreshToken, | ||
| "isNewUser": true]) | ||
| } | ||
| _ = try? await auth.signInAnonymously() | ||
| 
     | 
||
| // Then: Wait for a period to ensure the inverted expectation is not fulfilled. | ||
| await fulfillment(of: [streamCancelledExpectation], timeout: 1.0) | ||
| 
     | 
||
| // And explicitly check that the loop only ever ran once. | ||
| XCTAssertEqual(iteration, 1, "The stream should have only emitted its initial value.") | ||
| } | ||
| 
     | 
||
| @available(iOS 18.0, *) | ||
| func testAuthStateChangesStreamYieldsNilOnSignOut() async throws { | ||
| // Given | ||
| let initialNilExpectation = expectation(description: "Stream should emit initial nil user") | ||
| let signInExpectation = expectation(description: "Stream should emit signed-in user") | ||
| let signOutExpectation = expectation(description: "Stream should emit nil after sign-out") | ||
| try? auth.signOut() | ||
| 
     | 
||
| var iteration = 0 | ||
| let task = Task { | ||
| for await user in auth.authStateChanges { | ||
| switch iteration { | ||
| case 0: | ||
| XCTAssertNil(user, "The initial user should be nil") | ||
| initialNilExpectation.fulfill() | ||
| case 1: | ||
| XCTAssertNotNil(user, "The stream should yield the signed-in user") | ||
| signInExpectation.fulfill() | ||
| case 2: | ||
| XCTAssertNil(user, "The stream should yield nil after sign-out") | ||
| signOutExpectation.fulfill() | ||
| default: | ||
| XCTFail("The stream should not have emitted more than three values.") | ||
| } | ||
| iteration += 1 | ||
| } | ||
| } | ||
| 
     | 
||
| // Wait for the initial nil value. | ||
| await fulfillment(of: [initialNilExpectation], timeout: 1.0) | ||
| 
     | 
||
| // Sign in a user. | ||
| setFakeGetAccountProviderAnonymous() | ||
| setFakeSecureTokenService() | ||
| rpcIssuer.respondBlock = { | ||
| try self.rpcIssuer.respond(withJSON: ["idToken": "TEST_ACCESS_TOKEN", | ||
| "refreshToken": self.kRefreshToken, | ||
| "isNewUser": true]) | ||
| } | ||
| _ = try await auth.signInAnonymously() | ||
| await fulfillment(of: [signInExpectation], timeout: 2.0) | ||
| 
     | 
||
| // When | ||
| try auth.signOut() | ||
| 
     | 
||
| // Then | ||
| await fulfillment(of: [signOutExpectation], timeout: 2.0) | ||
| task.cancel() | ||
| } | ||
| } | ||
      
      Oops, something went wrong.
        
    
  
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.