gpt4 book ai didi

android - Coroutine Kotlin Android with Retrofit

转载 作者:行者123 更新时间:2023-11-29 23:15:30 25 4
gpt4 key购买 nike

class Service{
interface RedditApi {
@GET("/top.json")
fun getTop(@Query("after") after: String,
@Query("limit") limit: String)
: Deferred<Response<News>>;
}
}
val okHttpClient = OkHttpClient.Builder()
.readTimeout(40, TimeUnit.SECONDS)
.addInterceptor { chain ->
val ongoing = chain.request().newBuilder()
ongoing.addHeader("Cache-Control", "no-cache")
ongoing.addHeader("User-Agent", System.getProperty("http.agent"))
//ongoing.addHeader("Authorization", val.trim());
chain.proceed(ongoing.build())
}
.connectTimeout(40, TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.baseUrl( "/rest/s1/mobile/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.client(okHttpClient)
.build()
redditApi = retrofit.create(Service.RedditApi::class.java)

好的,我知道了,我正在尝试对协程进行改造。我转到我的 Activity 并像下面那样实现它。我收到错误 dispatchers.main Unresolved 引用 main。我正在使用 kotlin 1.3.21。另外我的另一个问题是,如果用户在 Activity 上单击返回怎么办?我怎样才能取消协程操作?就像在 Java 中一样,我曾经用改造来做 call.cancel()。它取消了调用。

class MainActivity : AppCompatActivity(), Fightable {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)


CoroutineScope(Dispatchers.IO).launch {
val request = App.redditApi.getTop("after", "limit")
withContext(Dispatchers.Main) {
try {
val response = request.await()
if (response.isSuccessful) {
val news: News? = response.body()
//Do something with response e.g show to the UI.
} else {
}
} catch (e: HttpException) {
} catch (e: Throwable) {
}
}
}}}

最佳答案

您需要创建协程上下文的单个实例,并为其定义一个作业。
val 作业 = 作业 ()
val coroutineScope = CoroutineContext(Dispatchers.Main+job)

并使用声明的范围开始工作,当您想取消工作时,只需调用 job.cancel() 即可取消所有当前和即将进行的工作。

关于android - Coroutine Kotlin Android with Retrofit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55441263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com