FirebaseMessagingService Cancels CoroutineScope Before the Job is Finished

22 hours ago 1
ARTICLE AD BOX

In the following code snippet, I'm trying to execute a suspend function MessageHandler.handleMessage() in onMessageReceived(), however the function doesn't finish becuase the ioScope is canceled due to onDestroy() being called.

class FcmService : FirebaseMessagingService() { companion object { private const val FCM_KEY_MESSAGE = "message" } private val conversationsRepo: ConversationsRepoImpl by inject() private val chatMessagesRepo: ChatMessagesRepoImpl by inject() private val ioScope = CoroutineScope(Dispatchers.IO) override fun onMessageReceived(message: RemoteMessage) { super.onMessageReceived(message) val message = message.data[FCM_KEY_MESSAGE] ?: return ioScope.launch { try { MessageHandler.handleMessage( conversationsRepo, chatMessagesRepo, message ) } catch (e: Exception) { Log.e("xxx", "Error: ${e.message.toString()}") } } } override fun onDestroy() { super.onDestroy() Log.d("xxx", "onDestroy()") ioScope.cancel() } }

Here is the log:

onDestroy() Error: Job was cancelled

How can I make the suspend function finish?

Read Entire Article