title: Coroutine Kotlin Android with Retrofit
body: <pre><code>class Service{
      interface  RedditApi {
          @GET("/top.json")
          fun getTop(@Query("after") after: String,
                     @Query("limit") limit: String)
                  : Deferred&lt;Response&lt;News&gt;&gt;;
      }
  }
   val okHttpClient = OkHttpClient.Builder()
              .readTimeout(40, TimeUnit.SECONDS)
              .addInterceptor { chain -&gt;
                  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)
  </code></pre>
  
  <p>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. </p>
  
  <pre><code>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) {
                      }
                  }
              }}}
  </code></pre>