gpt4 book ai didi

android - Firebase Cloud Functions是否在Android的主线程之外运行?

转载 作者:行者123 更新时间:2023-12-02 13:10:48 25 4
gpt4 key购买 nike

与Firestore调用类似,Firebase Cloud Functions在启动时是否会在Android的主线程上运行?
对于Firestore数据库调用,默认情况下处理后台线程。
Do we need to use background thread for retrieving data using firebase?

The Firebase Database client performs all network and disk operations off the main thread.

The Firebase Database client invokes all callbacks to your code on the main thread.

So network and disk access for the database are no reason to spin up your own threads or use background tasks. But if you do disk, network I/O or CPU intensive operations in the callback, you might need to perform those off the main thread yourself.


观察
使用Kotlin协程在Android的ViewModel中的 IO线程上启动Firebase Cloud Function,并在 Main线程上返回。但是,如果默认情况下在主线程上未运行Cloud Functions,则不需要 flowOn(Dispatchers.IO)withContext(Dispatchers.Main)来指定线程。
SomeViewModel.kt
fun someMethod() {
repository.someCloudFunction().onEach { resource ->
withContext(Dispatchers.Main) {
// Do something with returned resource here.
}
}.flowOn(Dispatchers.IO).launchIn(viewModelScope)
}
SomeRepository.kt
fun someCloudFunction(contentSelected: FeedViewEventType.ContentSelected) = flow {
try {
val content = contentSelected.content
FirebaseFunctions.getInstance(firebaseApp(true))
.getHttpsCallable("SOME_CLOUD_FUNCTION").call(
hashMapOf(
BUILD_TYPE_PARAM to BuildConfig.BUILD_TYPE,
CONTENT_ID_PARAM to content.id,
CONTENT_TITLE_PARAM to content.title,
CONTENT_PREVIEW_IMAGE_PARAM to content.previewImage))
.continueWith { task ->
(task.result?.data as HashMap<String, String>)
}
// Use 'await' to convert callback to coroutine.
.await().also { response ->
// Do something with response here.
}
} catch (error: FirebaseFunctionsException) {
// Do something with error here.
}
}
期望
假定在默认情况下云函数不在主线程上运行,则可以安全地删除在 IO线程上运行cloud函数并在 Main线程上返回响应的显式调用。
SomeViewModel.kt
fun someMethod() {
repository.someCloudFunction().onEach { resource ->
// Do something with returned resource here.
}.launchIn(viewModelScope)
}

最佳答案

您链接的我的答案是关于Firebase Realtime Database客户端的,它与Firebase Functions客户端是分开的。
也就是说,所有Firebase客户端应遵循相同的规则,因此我希望Functions客户端也可以在主线程之外执行所有网络I / O。
那不是你所看到的吗?

Android SDK for Functions的代码位于开源SDK中的here中。

关于android - Firebase Cloud Functions是否在Android的主线程之外运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62855244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com