Coroutine Kotlin Android(带改造)

时间:2019-03-31 13:15:11

标签: android kotlin kotlin-coroutines

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我有,我正在尝试对Coroutine进行改造。我去做我的活动并像下面那样实现它。我得到了error dispatchers.main尚未解决的参考main。我正在使用kotlin 1.3.21。我的另一个问题是,如果用户单击活动,该如何取消协程操作呢?就像在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) {
                    }
                }
            }}}

1 个答案:

答案 0 :(得分:1)

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

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