I have the below function which is completely 2 task asynchronously to upload data to Firebase. I need the 2nd function to return the documentId of new document created in Firebase and once done the main function returns this documentId so I can use it elsewhere. However, the return function is completing before the Firebase upload async functions have run and hence is returning an empty string. How can I fix this?
suspend fun profileLiked(): String {
var documentId: String = ""
CoroutineScope(Dispatchers.IO).launch {
supervisorScope {
try {
async {
firstFunctionToUploadAysnchronouslyToFirebase()
}.await()
async {
documentId = secondFunctionToUploadAsynchronouslyToFirebase()
}.await()
} catch (error: Exception) {
throw error
}
}
}
//this return function is getting called first and returning the empty string instead of the documentId result from secondFunctionToUploadAsynchronouslyToFirebase()
return documentId
}
2
Answers
There is no issue with above code and it is doing what it intended.
If you need documentId which is returned from the
secondFunctionToUploadAsynchronouslyToFirebase
, then you need to wait on parent coroutine before you return the documentId.Additional info added as comments.
Add
.join()