【问题标题】:Do I need to mention the coroutine dispatcher while working with Retrofit and Room?在使用 Retrofit 和 Room 时,我是否需要提及协程调度程序?
【发布时间】:2022-07-15 11:29:51
【问题描述】:

最近我看到了这个 - Most data sources already provide main-safe APIs like the suspend method calls provided by Room or Retrofit. Your repository can take advantage of these APIs when they are available.

这是什么意思?调度员在后台Dispatcher.IO 用于改造和房间吗?或者我是否需要在提出请求时明确提及?谢谢。

withContext(Dispatchers.IO) {
    // Some retrofit call or room query
}

【问题讨论】:

    标签: android kotlin retrofit android-room kotlin-coroutines


    【解决方案1】:

    不,您无需提及 Retrofit 和 Room 的调度员。对于 Room,当您将 dao 函数标记为挂起乐趣时,可以保证它不会阻塞主线程。

    你可以阅读这篇文章https://medium.com/androiddevelopers/room-coroutines-422b786dc4c5

    来自文章

    Room 调用 CoroutinesRoom.execute 挂起函数,该函数切换到后台调度程序,具体取决于数据库是否打开以及我们是否处于事务中。

    【讨论】:

    • 谢谢。改造也有参考吗?我看改造源代码,虽然我在那里找不到任何调度程序))
    • 不,但在 github,他们宣布改造在 2.6.0 版本中支持挂起修饰符-> 来自 changle 日志的github.com/square/retrofit/blob/master/…:“在幕后,这就像定义为有趣的用户(... ): Call 然后使用 Call.enqueue 调用。您还可以返回 Response 以访问响应元数据。"
    【解决方案2】:

    不,在调用 Retrofit 和 Room 的 suspend 函数时不需要切换上下文。我不确定他们是否在后台使用Dispatcher.IO,也许他们使用由线程池组成的自定义上下文,但保证在后台线程中调用。

    例如,您可以在ViewModel 类中调用suspend Dao 函数,如下所示:

    viewModelScope.launch {
        val user dao.getCurrentUser()
        // Update UI using user
    }
    

    假设getCurrentUser()suspend 函数:

    suspend fun getCurrentUser(): User
    

    【讨论】:

    • 如果知道添加特定调度程序是否真的对性能有任何重大影响,可能会导致这些操作在更糟糕的线程上执行,如果这甚至有意义的话,这将是非常有趣的
    【解决方案3】:

    将 Retrofit HTTP 请求方法和 Room DAO 查询方法标记为 suspend 会告诉各自的库为您执行异步工作,这意味着您根本不必使用 Dispatchers.IO 显式更改线程。

    此外,即使 Room DAO 方法没有标记为 suspend,但它返回一个包裹在 Kotlin 的 Flow 或 RxJava 的 Flowable 或 Jetpack 的 LiveData 中的值,Room 也会异步执行这些查询也为你。 As per the documentation.

    话虽如此,在这种情况下,您应该仍然启动协程,无论何时使用 lifecycleScopeviewModelScope 调用异步非阻塞方法,具体取决于您调用它们的位置( Activity/Fragment 或 ViewModel)来利用挂起函数的全部功能。 lifecycleScopeviewModelScope 默认使用 Dispatchers.Main.immediate,如前所述,您不需要更改 Dispatchers。

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 2017-06-03
      • 1970-01-01
      • 2018-09-20
      • 2020-01-07
      • 2016-07-18
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多