Nicolas Verinaud
09/22/2021, 10:59 AMinterface CanRetrieveAuthorizationToken {
suspend fun getToken(): String
}
The corresponding protocol :
public protocol CanRetrieveAuthorizationToken {
/**
@note This method converts instances of CancellationException to errors.
Other uncaught Kotlin exceptions are fatal.
*/
func getToken(completionHandler: @escaping (String?, Error?) -> Void)
}mbonnin
09/22/2021, 11:05 AMNicolas Verinaud
09/22/2021, 1:29 PMNicolas Verinaud
09/22/2021, 1:31 PMgetToken method ? Or add a cancelGetToken method to the interface ?mbonnin
09/22/2021, 1:35 PMRxSwift and/or Combine so I guess it has a way to handle cancellation from them and if you don't want to use these frameworks, it should be doable too. Maybe not easy thoughNicolas Verinaud
09/22/2021, 2:11 PMsuspend function is not used by swift but implemented by swift. The swift code needs a way to know when to cancel its job.mbonnin
09/22/2021, 2:14 PMmbonnin
09/22/2021, 2:15 PMCancellableContinuation instead?Nicolas Verinaud
09/22/2021, 2:25 PMNicolas Verinaud
09/22/2021, 2:50 PMgetToken method like this :
fun getToken(onSuccess: (String) -> Unit, onError: (Throwable) -> Unit): Disposable
This allows swift code to be cancellable by returning an instance of Disposable which is a class I created inspired by C# (wrapping a method executed when the disposable is disposed aka cancelled).
I then wrapped the call to the new getToken method in a suspend function using suspendCancellableCoroutine to make it usable alongside other suspending function (in my case http calls using ktor). More info here : https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/suspend-cancellable-coroutine.html.
Thanks @mbonnin for the hint about CancellableContinuation 🙌Nicolas Verinaud
09/22/2021, 2:52 PM