user3278732
user3278732

Reputation: 1724

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. 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. 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.

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) {
                    }
                }
            }}}

Upvotes: 2

Views: 1436

Answers (1)

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.

Upvotes: 1

Related Questions