Hi, I need some help :slightly_smiling_face: I'm w...
# getting-started
m
Hi, I need some help 🙂 I'm working on a KMP project targeting Android and iOS, and I think the issue might be with my Kotlin code, so I hope someone can help me here. I'm having trouble signing out using Firebase Auth from GitLiveApp/firebase-kotlin-sdk. When I call onSignOutClicked in
ProfileScreen
, my app navigates to
AuthScreen
using the
signOut()
callback passed as a constructor argument to
ProfileScreen
. After that, my
AuthViewModel
collects
authService.currentUser
the same way it’s done in
ProfileViewModel
inside the
init
block. However, it still returns a non-null
FirebaseUser
, even though I already signed out. I’ll attach some code in a reply. Thanks in advance!
Copy code
@Composable
fun ProfileScreen() {
 val uiState by viewModel.uiState.collectAsState()
 when (val state = uiState) {
    is ProfileUiState.Success -> {
        ProfileScreen (onSignOutClicked = {viewModel.onSignOut()})
    }
    is ProfileUiState.SignedOut -> {
        LaunchedEffect(Unit) {
            signOut()
        }
    }
}

class ProfileViewModel(private val authService: AuthService) : ViewModel() {

    init {
        viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            authService.currentUser.collect { user ->
                _uiState.value = if (user != null && user.isEmailVerified) {
                    ProfileUiState.Success(currentUser = user)
                } else {
                    ProfileUiState.SignedOut
                }
            }
        }
    }
    fun onSignOut() {
        viewModelScope.launch {
            authService.signOut()
        }
    }
}

import dev.gitlive.firebase.auth.FirebaseAuth

class AuthServiceImpl(
    val auth: FirebaseAuth
) : AuthService {
    // public expect final val authStateChanged: Flow<FirebaseUser?>
    override val currentUser = auth.authStateChanged
    override suspend fun signOut() {
            auth.signOut()
    }
}

@Composable
fun AuthScreen(
    [...]
) {
    val authState by viewModel.authState.collectAsStateWithLifecycle()

    LaunchedEffect(authState) {
        when (val state = authState) {
            is AuthState.Authenticated -> {
                navigateToDashboard()
            }
            is AuthState.Unauthenticated -> {
                navigateToLogin()
            }
        }
    }
}

class AuthViewModel(authService: AuthService) : ViewModel() {

    init {
        viewModelScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            authService.currentUser.collect { firebaseUser ->
                _authState.update {
                    if (firebaseUser != null && firebaseUser.isEmailVerified){
                        AuthState.Authenticated()
                    } else {
                        AuthState.Unauthenticated
                    }
                }
            }
        }
    }
}