如何与Kotlin协程一起使用Fuel [英] How to use Fuel with a Kotlin coroutine

查看:268
本文介绍了如何与Kotlin协程一起使用Fuel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Android应用中,我试图使用燃料在一个Kotlin协程.我的第一个尝试是在这样的包装器内使用同步模式:

Within an Android app, I'm trying to use Fuel to make an HTTP request within a Kotlin coroutine. My first try is to use the synchronous mode inside a wrapper like this:

launch(UI) {
    val token = getToken()
    println(token)
}

suspend fun getToken(): String? {
    var (request, response, result = TOKEN_URL.httpGet().responseString()
    return result.get()
}

但是返回的是android.os.NetworkOnMainThreadException. Fuel文档中提到了.await()和.awaitString()扩展名,但我还没有弄清楚.

But that is returning an android.os.NetworkOnMainThreadException. The Fuel documentation mentions .await() and .awaitString() extensions but I haven't figured it out.

从Android应用程序的主UI线程在Kotlin协程中发出Fuel http请求的最佳方法是什么?坚持下去-非常感谢...

What is the best way to make a Fuel http request within a Kotlin coroutine from the main UI thread in an Android application? Stuck on this - many thanks...

推荐答案

suspend fun调用阻止代码不会自动将其转换为挂起代码.您调用的函数本身必须已经是suspend fun.但是,正如您已经提到的,Fuel对Kotlin协程具有一流的支持,因此您不必自己编写.

Calling blocking code from a suspend fun doesn't automagically turn it into suspending code. The function you call must already be a suspend fun itself. But, as you already noted, Fuel has first-class support for Kotlin coroutines so you don't have to write it yourself.

我研究了Fuel的

这应该足以使您前进.例如,您可以编写一个简单的函数,如下所示:

This should be enough to get you going. For example, you might write a simple function as follows:

suspend fun getToken() = TOKEN_URL.httpGet().awaitStringResponse().third

这篇关于如何与Kotlin协程一起使用Fuel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆