【发布时间】:2021-08-23 02:11:50
【问题描述】:
我正在使用 MVVM 设计模式开发一个 Android 应用程序。
我有一个扩展 FirebaseMessagingService 的类 FCMService。
如您所知,FCMService 会覆盖 onMessageReceived(remoteMessage: RemoteMessage) 函数。
所以,每当我在onMessageReceived() 函数中收到消息时,我都想通过存储库将其保存到房间数据库中。
它看起来像下面的代码。
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)
}
}
}
我阅读了stackoverflow post 并发现onMessageReceived() 函数在后台线程中执行,并且在 onMessageReceived(RemoteMessage message) 中完成的所有工作都应该同步完成。
所以,这里是我的问题,请
-
我应该在
onMessageRecevied()函数中使用CoroutineScope(Dispatchers.IO).lauch {}吗? -
如果不是,那么我可以只使用普通函数,而不是存储库中的挂起函数,我可以从
onMessageReceived()调用它,而无需CoroutineScope(Dispatchers.IO).launch {}。请问从建筑设计的角度来看是否正确? -
这是一个关于协程的问题,但是,正如您所见,我在 IO 线程中通过
FCMService中的CoroutineScope(Dispatchers.IO).lauch{ repository.save(remoteMessage) }启动了一个新协程,但我还通过Repository中的withContext(Dispatchers.IO) { someDAO.save(removeMessage) }将 coroutineContext 从 IO 切换到了 IO。我觉得withContext(Dispatchers.IO) { someDAO.save(removeMessage) }是不必要的,因为我是从IO切换到IO。请问我说的对吗?
【问题讨论】:
标签: android firebase-cloud-messaging coroutine