okhttp icon indicating copy to clipboard operation
okhttp copied to clipboard

Adding a callback interface to release resources upon canceling a Call

Open ypyu2000 opened this issue 7 years ago • 3 comments

We need to clean up resources in some interceptors when a call is canceled. To be specific, we want to release some resources when Call$cancel() is called. Please let us know if there is an existing way to do this.

We could not find a way to do it after exploring and browsing the code base. Since the RealCall class is final, it cannot be extended to modify the behavior of cancel(). We have a proposal that is noninvasive and would like to upstream.

  • Modify Call interface to expose a method "addCancelCallback(CancelCallback cancelCallback)" and add a CancelCallback interface with onCancelled().
  • The RealCall$cancel() will be modified to make call to CancelCallback$onCancelled()

The detailed changes are listed at https://gist.github.com/nsivabalan/58ddf3cac8711ab886824a7043dec2f0

Thanks

James

ypyu2000 avatar Apr 27 '19 02:04 ypyu2000

You could use a custom Call.Factory to create a delegating Call that just reports cancel() calls right?

class CallWithListener(private val delegate: Call) : Call by delegate {

  private var cancelCallback: (() -> Unit)? = null

  fun addCancelCalback(cancelCallback: () -> Unit) {
    this.cancelCallback = cancelCallback
  }

  override fun cancel() {
    delegate.cancel()
    cancelCallback?.invoke()
  }
}

fun callFactorySample() {
  
  val delegate = OkHttpClient.Builder().build()
  
  val decoratingFactory = object : Factory {
    override fun newCall(request: Request): Call {
      return CallWithListener(delegate.newCall(request))
          .also { 
            it.addCancelCalback { 
              // Implement callback here?
            }
          }
    }
  }

  // Retrofit or something similar
  Retrofit.Builder()
      .callFactory(decoratingFactory)
      // ...
      .build()
}

ZacSweers avatar Apr 27 '19 03:04 ZacSweers

No plans to add new APIs here.

swankjesse avatar Apr 29 '19 02:04 swankjesse

Thanks Zac for your suggestion. We are trying out the proposed suggestion.

ypyu2000 avatar May 12 '19 05:05 ypyu2000