【问题标题】:Is it better to call .enqueue in a normal function or .execute in a kotlin suspend function?在普通函数中调用 .enqueue 还是在 kotlin 挂起函数中调用 .execute 更好?
【发布时间】:2021-01-20 06:58:57
【问题描述】:

这是我已经知道的:
Retrofit 有enqueue 函数和execute 函数。 enqueue 函数在不同的(后台)线程上执行,然后使用回调返回响应。 execute 函数在调用线程上执行并直接返回响应。 enqueue 可以在 UI 线程上调用,而 execute 不应该在 UI 线程上调用。

但我现在想知道,以下两个选项中哪个更好。

在普通函数中调用enqueue

fun makeRequest() {
    getCall().enqueue(
        object : Callback<ResponseBody> {
            override fun onResponse(
                call: Call<ResponseBody>,
                response: Response<ResponseBody>
            ) {
                
                if (response.isSuccessful) {
                    //unsuccessful
                }
                //successful
            }
            
            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                //failed
            }
            
        }
    )
}

或在后台线程的挂起函数中调用execute

suspend fun makeRequest() = withContext(Dispatchers.IO) {
    val call = getCall()
    
    try {
        val response = call.execute()
        
        if (!response.isSuccessful) {
            //unsuccessful
        }
        
        //successful
    } catch (t: Throwable) {
        //failed
    }
}

其中哪一个更可取?

【问题讨论】:

    标签: android kotlin retrofit2 kotlin-coroutines


    【解决方案1】:

    协程有更简洁的语法,所以这是一个优点。而且如果你熟悉协程 SupervisorJob,你可以更轻松地取消请求组。除此之外,它们在很大程度上是相同的,只是哪个后台线程被用于请求。但是 Retrofit 已经内置了协程支持,所以你的第二个版本可以比你有的更干净:

    suspend fun makeRequest() { // Can be called from any dispatcher
        try {
            val response = getCall().awaitResponse()
            
            if (!response.isSuccessful) {
                //unsuccessful
            }
            
            //successful
        } catch (t: Throwable) {
            //failed
        }
    }
    

    【讨论】:

    • 我什至不知道 awaitResponse 函数,因为我发现的所有 Retrofit 文档都使用 Java。是否有用于改造的 Kotlin 文档?还是其他地方的扩展功能?
    • 我在文档中没有找到。您可以在源代码中查找 KotlinExtensions.kt 文件以查看那里可用的内容。 github.com/square/retrofit/blob/master/retrofit/src/main/java/… 并查看更改日志中 2.6.0 下的注释,了解如何使您的接口使用 suspend 函数,以便在协程中更简单地使用它们(基本上,只需将您的函数标记为 suspend)。 github.com/square/retrofit/blob/master/CHANGELOG.md
    猜你喜欢
    • 1970-01-01
    • 2019-10-10
    • 2018-06-16
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多