Reputation: 4302
I have used the suspend routine builder to make the Firebase Tasks's move away from async listener based code to coroutine-based code.
This is my suspendcoroutine via which I achieve the coroutine behavior.
suspend fun <T> Task<T>.awaitTask(): T =
suspendCoroutine { continuation ->
addOnCompleteListener { task ->
if (task.isSuccessful) {
continuation.resume(task.result!!)//what to do if task.result is null
} else {
continuation.resumeWithException(task.exception!!)
}
}
}
This is how I invoke it
firebase.createUserWithEmailAndPassword(userCredentials.email!!, userCredentials.password!!).awaitTask()
All works well until we execute a task which has a possibility of a null result. Like .
firebase.currentUser?.updateProfile(profileUpdates)?.awaitTask()
Here upon successfully updation , task.result is null. In that case what should be passed to continuation.resume?.
Upvotes: 1
Views: 1946
Reputation: 200158
Your return type should be nullable because Task.getResult()
is nullable:
suspend fun <T> Task<T>.await() : T? = ...
If you use it to get a non-nullable result, then enforce non-nullability at the use site and not inside the implementation.
However, why do you bother reimplementing this when it's already defined in kotlinx-coroutines-play-services
?
Upvotes: 5