agoda-com / agoda-com/ninjato

Update Nijato Extensions to cancel suspend Calls silently

未關閉
#23 1 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視
enhancement
主要語言
Kotlin
星號
114
分支
9
PR 合併指標
30 天內沒有已合併 PR

描述

# Feature request

## Type

Improvement - make what we have better

## Is your feature request related to a problem?

After the suspending functionality PR, a `Call.Failure` will be returned even if it's from a Kotlin [CancellationException](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.cancellation/-cancellation-exception/):
```
suspend inline fun Api.callAsync(crossinline receiver: suspend Api.() -> T): Call = try {
Call.Success(receiver(this))
} catch (throwable: Throwable) {
Call.Failure(throwable)
}
```

that means callers need to handle this canceled result to prevent some error popup might be presented to users unexpectedly.

## Describe the solution you'd like

Rethrow `CancellationException` to the caller, and this `CancellationException` will be ignored by the coroutines' [exception handlers](https://kotlinlang.org/docs/exception-handling.html#cancellation-and-exceptions).

```
suspend inline fun Api.callAsync(crossinline receiver: suspend Api.() -> T): Call = try {
Call.Success(receiver(this))
} catch (throwable: Throwable) {
+ if (throwable is CancellationException) {
+ throw throwable
+ }
Call.Failure(throwable)
}
```

The benefits of this change
1. Can reduce the boilerplate code
2. Caller won't forget to handle the cancellation result from `Call.Failure(throwable)`

## Additional context

Rethrow CancellationException might be a normal practice on Coroutines. I found these articles

... we catch CancellationException just to execute some actions when a coroutine has been cancelled, but we throw it again to avoid stopping the cancellation.
... in case you want to catch a generic Exception, you should remember to rethrow it in case its actual type is CancellationException otherwise you’ll also suppress the cancellation of coroutines.

from [Kotlin Coroutines in Android — Part 5](https://medium.com/kinandcartacreated/kotlin-coroutines-in-android-part-5-64dcb60570f6)

... Do note that if something throws CancellationException you are generally expected to rethrow it so upstream objects are notified about the cancellation

from [How to ignore JobCancellationException?](https://stackoverflow.com/questions/54870443/how-to-ignore-jobcancellationexception)

Also, this one is related to our topic.[ Kotlin: How to bypass CancellationException](https://stackoverflow.com/questions/62220286/kotlin-how-to-bypass-cancellationexception)

貢獻指南

開啟貢獻指南

評估

這個 Issue 還沒有評估資料。

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。