I'm working on a Kotlin Multiplatform (KMP) project and I'm trying to implement a Firebase Authentication DataSource inside androidMain. Even after adding the Firebase dependencies, the compiler cannot resolve the .await() extension and the .user property on the Auth Task.
My Setup:
Kotlin Version: 2.0.0 (ou a sua versão)
Gradle Version: 8.x
Project: Kotlin Multiplatform (Compose Multiplatform)
My Code (FirebaseAuthDataSource.kt in androidMain):
Kotlin
interface AuthRemoteRepository {
suspend fun login(email: String, password: String): Result<UserToken>
}
class FirebaseAuthDataSource(
private val auth: FirebaseAuth
) : AuthRemoteRepository {
override suspend fun login(email: String, password: String): Result<UserToken> {
return try {
val authResult = auth.signInWithEmailAndPassword(email, password)
// Error here: Unresolved reference 'user'
val user = authResult.user ?: throw IllegalStateException("User is null")
// Error here: Unresolved reference 'await'
val tokenResult = user.getIdToken(true).await()
Result.success(UserToken(tokenResult.token ?: ""))
} catch (e: Exception) {
Result.failure(e)
}
}
}
My build.gradle.kts (:data module):
Kotlin
kotlin {
androidTarget()
sourceSets {
val androidMain by getting {
dependencies {
implementation(platform("com.google.firebase:firebase-bom:33.10.0"))
implementation("com.google.firebase:firebase-auth")
// I tried adding this, but it still doesn't work
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.10.2")
}
}
}
}
What I've tried:
Adding import kotlinx.coroutines.tasks.await, but the IDE says it doesn't exist.
Cleaning and Rebuilding the project.
Invalidating Caches and Restarting Android Studio.
Checking the external libraries: kotlinx-coroutines-android is there, but I can't find tasks.await in the classpath.
How can I properly import the .await() extension for Firebase Tasks in a KMP module?
The line where you call await() is perfectly fine. You get an error there because the user variable is not properly defined.
That happens in the line above, though, and here is where the actual problem lies: You try to access authResult.user, which already fails with this compile error:
> Unresolved reference 'user'.
The reason for that is that authResult is not really of type AuthResult, and therefore you cannot access its user property. It is, in fact, a Task<AuthResult> instead. So, to unwrap the AuthResult from the Task you need to call await() on it first:
val user = authResult.await().user
(or simply add await() to the line above where authResult is defined)
With this out of the way the rest of your code should work as expected.