I am developing an Android application using MVVM design pattern.
I have a class FCMService
that extends FirebaseMessagingService
.
As you may know, the FCMService
overrides onMessageReceived(remoteMessage: RemoteMessage)
function.
So, whenever I receive a message in onMessageReceived()
function, I want to save it to room database via a repository.
It looks like the code below.
class FCMService : FirebaseMessagingService(), KodeinAware {
override val kodein by closestKodein()
private val repository: Repository by instance()
private val scope: CoroutineScope by instance()
override fun onNewToken(token: String) {
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
CoroutineScope(Dispatchers.IO).lauch{ repository.save(remoteMessage) }
}
}
class Repository {
suspend fun save(remoteMessage: RemoteMessage) {
withContext(Dispatchers.IO) {
someDAO.save(removeMessage)
}
}
}
I read a stackoverflow post and found out that the onMessageReceived()
function executes in background thread and all work that is done within onMessageReceived(RemoteMessage message) should be done synchronously.
So, here are my questions please
Should I use
CoroutineScope(Dispatchers.IO).lauch {}
inonMessageRecevied()
function?If no, then I can just use normal function, not suspend function in repository and I can call it from
onMessageReceived()
withoutCoroutineScope(Dispatchers.IO).launch {}
. Is it correct in terms of architectural design point of view please?It's a question about Coroutine but, as you can see that I launched a new coroutine in IO thread by
CoroutineScope(Dispatchers.IO).lauch{ repository.save(remoteMessage) }
inFCMService
but I also switch the coroutineContext from IO to IO bywithContext(Dispatchers.IO) { someDAO.save(removeMessage) }
inRepository
. I feel thatwithContext(Dispatchers.IO) { someDAO.save(removeMessage) }
is unnecessary because I am switching from IO to IO. Am I right please?