Do Firebase Cloud Functions run off of the main thread on Android when initiated similar to Firestore calls?
For Firestore database calls background threading is handled by default.
i.e. 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.
Observe
A Firebase Cloud Function is launched on an IO
thread within a ViewModel in Android using Kotlin coroutines and returned on the Main
thread. However, if Cloud Functions are not run on the main thread by default flowOn(Dispatchers.IO)
and withContext(Dispatchers.Main)
are not required to specify the threads.
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.
}
}
Expect
The explicit call to run the cloud function on the IO
thread and return the response on the Main
thread can be removed safely given that the cloud function does not run on the main thread by default.
SomeViewModel.kt
fun someMethod() {
repository.someCloudFunction().onEach { resource ->
// Do something with returned resource here.
}.launchIn(viewModelScope)
}