Search code examples
androidkotlinretrofit2deferredkotlinx.coroutines

Retrofit 2 with coroutine call adapter factory cancel request


I am trying to implement dynamic search functionality in my android application using retrofit2 with coroutine call adapter factory. When user type keyword and if keyword length is valid then app make request to server. In single request i can request like below

launch(UI) {
        try {
            val user = Client.provideService().getUsers()
            //do sometihng with user.await()
        }catch (e: Exception){
            //Handle exception
        }
    }

but what if i want to cancel every previous request and make new request when user changes the editable ? I search a lot for an example but i cant find anything useful. Thanks for help.


Solution

  • If you want to cancel a coroutine, you can do that as explained in this guide. You need to invoke cancel on the Job that is returned from launch:

    val job = launch {
       //...
    }
    
    job.cancel() // cancels the job 
    

    But it's very important to know that Coroutine cancellation is cooperative, i.e. the block executed in the coroutine needs to react on the cancellation from outside the coroutine. You can check the state with isActive as described here.

    As for your example, you would have to be able to cancel the computation of Client.provideService().getUsers() as soon as isActive becomes true.