我必须在后台线程中执行http请求(Retrofit 2)。
方法1:
suspend fun getTraidersList(): TransportResponse = withContext(Dispatchers.IO) {
val traderMonitorRestClient = RestClientFactory.createRestClient(TraderMonitorRestClient::class.java)
executeOperation { traderMonitorRestClient.getTraidersList() }
}
suspend private fun executeOperation(transportOperation: suspend () -> Response<*>): TransportResponse {
try {
val response: Response<*> = transportOperation()
return onResponse(response)
} catch (e: Throwable) {
return onNetworkFailure(e)
}
}
}
如您所见,方法getTraidersList()
是由withContext(Dispatchers.IO)
在后台线程中启动的。但是在方法executeOperation
中,我没有使用withContext(Dispatchers.IO)
。
好。很好。
方法2:
在方法withContext(Dispatchers.IO)
中也使用executeOperation
suspend fun getTraidersList(): TransportResponse = withContext(Dispatchers.IO) {
val traderMonitorRestClient = RestClientFactory.createRestClient(TraderMonitorRestClient::class.java)
executeOperation { traderMonitorRestClient.getTraidersList() }
}
suspend private fun executeOperation(transportOperation: suspend () -> Response<*>): TransportResponse = withContext(Dispatchers.IO) {
try {
val response: Response<*> = transportOperation()
onResponse(response)
} catch (e: Throwable) {
onNetworkFailure(e)
}
}
两种方法都能奏效。 但是哪种方法是正确的?也许这两种方法都是正确的?
答案 0 :(得分:1)
如果要在其他任何地方重用executeOperation
方法,则可以将其放入另一个线程中,但是就您而言,暂时不需要。
如果您想重用executeOperation
方法,这也可以工作。
suspend fun getTraidersList(): TransportResponse {
val traderMonitorRestClient = RestClientFactory.createRestClient(TraderMonitorRestClient::class.java)
executeOperation { traderMonitorRestClient.getTraidersList() }
}
suspend private fun executeOperation(transportOperation: suspend () -> Response<*>): TransportResponse = withContext(Dispatchers.IO) {
try {
val response: Response<*> = transportOperation()
onResponse(response)
} catch (e: Throwable) {
onNetworkFailure(e)
}
}