小编Kis*_*Tae的帖子

我应该在 FirebaseMessagingService 的 onMessageReceived() 中使用协程吗?

我正在使用 MVVM 设计模式开发 Android 应用程序。

我有一个FCMService扩展的类FirebaseMessagingService

如您所知,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) }
    }
}
Run Code Online (Sandbox Code Playgroud)
class Repository {
   suspend fun save(remoteMessage: RemoteMessage) {
      withContext(Dispatchers.IO) {
         someDAO.save(removeMessage)
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

我读了一篇 stackoverflow帖子,发现该onMessageReceived()函数在后台线程中执行,并且 …

android coroutine firebase-cloud-messaging

6
推荐指数
1
解决办法
2716
查看次数