简体   繁体   中英

Firebase async tasks to coroutines

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?.

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM