繁体   English   中英

在普通函数中调用 .enqueue 还是在 kotlin 挂起函数中调用 .execute 更好?

[英]Is it better to call .enqueue in a normal function or .execute in a kotlin suspend function?

这是我已经知道的:
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
    }
}

其中哪一个更可取?

协程有更清晰的语法,所以这是一个加分项。 如果您熟悉协程 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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM