191029 Firebase Task continueWith

這幾天在看 Firebase 的 Call functions from your app

https://firebase.google.com/docs/functions/callable

範例中,有一段程式碼如下

return functions    .getHttpsCallable("addNumbers")
    .call(data)
    .continueWith { task ->        // This continuation runs on either success or failure, but if the task        // has failed then task.result will throw an Exception which will be        // propagated down.        val result = task.result?.data as Map<String, Any>
        result["operationResult"] as Int
    }

  •  functions
com.google.firebase.functions.FirebaseFunctions

https://firebase.google.com/docs/reference/android/com/google/firebase/functions/FirebaseFunctions

  •  .getHttpsCallable("addNumbers")
 "addNumbers" 為 Cloud Function 的名稱


getHttpsCallable 回傳的是 HttpsCallableReference

https://firebase.google.com/docs/reference/android/com/google/firebase/functions/HttpsCallableReference.html


  • .call(data)
    傳入的是 addNumbers 可接受的參數
call 回傳的是 Task<HttpsCallableResult>


最後這 continueWith 用了 Lambda,對 Task 要有一定的熟悉度會比較知道它的來龍去脈。

對 Task 不熟悉的人,建議可閱讀 Become a Firebase Taskmaster!
https://firebase.googleblog.com/2016/09/become-a-firebase-taskmaster-part-1.html?utm_campaign=Firebase_culture_education_general_en_09-29-16&utm_source=Firebase&utm_medium=blog

這邊把 continueWith lambda 還原成 Kotlin

.continueWith(
                object: Continuation<HttpsCallableResult, Int> {
                    override fun then( task: Task<HttpsCallableResult>): Int {
                        val result = task.result?.data as Map<String, Any>
                        return result[ "operationResult" ] as Int
                    }
                })






留言

這個網誌中的熱門文章

泰文子音與字形之間的變化

AUTOMAXX UP-5HX 使用心得