-
Notifications
You must be signed in to change notification settings - Fork 7.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(firebaseui): move Firebase calls to ViewModel
- Loading branch information
1 parent
8fffb30
commit bc9912a
Showing
2 changed files
with
89 additions
and
46 deletions.
There are no files selected for viewing
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
61 changes: 61 additions & 0 deletions
61
auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FirebaseUIViewModel.kt
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package com.google.firebase.quickstart.auth.kotlin | ||
|
||
import androidx.lifecycle.ViewModel | ||
import com.google.firebase.auth.FirebaseAuth | ||
import com.google.firebase.auth.FirebaseUser | ||
import com.google.firebase.auth.ktx.auth | ||
import com.google.firebase.ktx.Firebase | ||
import kotlinx.coroutines.flow.MutableStateFlow | ||
import kotlinx.coroutines.flow.StateFlow | ||
import kotlinx.coroutines.flow.update | ||
|
||
class FirebaseUIViewModel( | ||
private val firebaseAuth: FirebaseAuth = Firebase.auth | ||
) : ViewModel() { | ||
private val _uiState = MutableStateFlow(UiState()) | ||
val uiState: StateFlow<UiState> = _uiState | ||
|
||
data class UiState( | ||
var status: String = "", | ||
var detail: String? = null, | ||
var isSignInVisible: Boolean = true | ||
) | ||
|
||
init { | ||
// Check if user is signed in (non-null) and update UI accordingly. | ||
showSignedInUser() | ||
} | ||
|
||
fun showSignedInUser() { | ||
val firebaseUser = firebaseAuth.currentUser | ||
updateUiState(firebaseUser) | ||
} | ||
|
||
fun signOut() { | ||
updateUiState(null) | ||
} | ||
|
||
private fun updateUiState(user: FirebaseUser?) { | ||
if (user != null) { | ||
_uiState.update { currentUiState -> | ||
currentUiState.copy( | ||
status = "Firebase User: ${user.displayName}", | ||
detail = "Firebase UID: ${user.uid}", | ||
isSignInVisible = false | ||
) | ||
} | ||
} else { | ||
_uiState.update { currentUiState -> | ||
currentUiState.copy( | ||
status = "Signed out", | ||
detail = null, | ||
isSignInVisible = true | ||
) | ||
} | ||
} | ||
} | ||
|
||
companion object { | ||
const val TAG = "FirebaseUIViewModel" | ||
} | ||
} |