Adding a callback interface to release resources upon canceling a Call
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
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()
}
No plans to add new APIs here.
Thanks Zac for your suggestion. We are trying out the proposed suggestion.