什么是anko bg的替代品?

时间:2019-05-15 05:22:41

标签: android kotlin anko kotlin-coroutines

我正在使用anko bg功能来管理后台任务。

代码如下

import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import com.github.kittinunf.result.Result
import org.jetbrains.anko.coroutines.experimental.bg

object AuthenticationService {
    suspend fun login(login: Login): Triple<Request, Response, Result<GenResponse, FuelError>> {
        return bg {
            HttpService.post<GenResponse>("/auth/login",login.toJsonString())
        }.await()
    }
}

它表明bg已过时,并要求我使用async(block)

如何用异步替换此后台任务?

4 个答案:

答案 0 :(得分:1)

考虑为各种后台任务创建自己的ThreadPoolExecutor,并将其用作协程分配器。

您总是可以看看Anko bg source code以作参考。

答案 1 :(得分:1)

您不应使用任何替代bg的方式,因为Fuel支持异步HTTP。您不需要任何后台线程即可执行请求。此外,Fuel具有first-class support for coroutines

答案 2 :(得分:0)

根据信息,您应该将其替换为协程的异步。 可能在以下方面:

return async(Dispatchers.IO) {
            HttpService.post<GenResponse>("/auth/login",login.toJsonString())
        }.await()

让我知道是否有帮助:)!

答案 3 :(得分:0)

另一种方法

suspend fun login(login: Login): Triple<Request, Response, Result<GenResponse, FuelError>> {
        return withContext(Dispatchers.Default) {
            HttpService.postNoAuth<GenResponse>("/auth/login", login.toJsonString())
        }
    }