简体   繁体   English

Coroutine Kotlin Android with Retrofit

[英]Coroutine Kotlin Android with Retrofit

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)

Okey I have that, am trying to use retrofit with Coroutine.好吧,我知道了,我正在尝试使用 Coroutine 进行改造。 I go to my activity and implement it like below.I get error dispatchers.main unresolved reference main.I am using kotlin 1.3.21.我转到我的活动并像下面一样实现它。我收到错误 dispatchers.main 未解析的引用 main。我正在使用 kotlin 1.3.21。 Also my other question is, what if user clicks back on the activity how can I cancel the coroutine operation?Like In Java I used to do call.cancel() with retrofit.It cancelled the call.另外我的另一个问题是,如果用户重新点击活动怎么办,我怎样才能取消协程操作?就像在 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) {
                    }
                }
            }}}

You need to create a single instance of coroutine context and also have a job defined to it.您需要创建协程上下文的单个实例,并为其定义一个作业。 val job = Job() val coroutineScope = CoroutineContext(Dispatchers.Main+job)

And start the work using the declared scope and when you want to cancel the work, you can simply call job.cancel() which cancels all current and upcoming works.并使用声明的范围开始工作,当您想取消工作时,您只需调用job.cancel()取消所有当前和即将进行的工作。

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

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