leandro
03/13/2021, 10:53 AMsuspendCancellableCoroutine
, do I need to cleanup the resources inside the error callback?
suspend fun isSessionValid(): Boolean = suspendCancellableCoroutine { continuation ->
lateinit var auth: Auth
val callback = object : AuthHandler {
override fun onSuccess(session: AuthUserSession) {
continuation.resume(session.isValid)
auth.release()
}
override fun onFailure(e: Exception) {
continuation.resumeWithException(e)
}
}
auth = builder.setAuthHandler(callback).build()
auth.getSession()
continuation.invokeOnCancellation { auth.release() }
}
Dominaezzz
03/13/2021, 10:58 AMleandro
03/13/2021, 10:59 AMDominaezzz
03/13/2021, 10:59 AMleandro
03/13/2021, 11:00 AMDominaezzz
03/13/2021, 11:04 AMleandro
03/13/2021, 11:04 AMDominaezzz
03/13/2021, 11:21 AMsuspend fun isSessionValid(): Boolean {
val latch = CompletableDeferred<AuthUserSession>()
val callback = object : AuthHandler {
override fun onSuccess(session: AuthUserSession) {
latch.complete(session)
}
override fun onFailure(e: Exception) {
latch.completeExceptionally(e)
}
}
val auth = builder.setAuthHandler(callback).build()
try {
auth.getSession()
val session = latch.await()
return session.isValid
} finally {
auth.release()
}
}
leandro
03/13/2021, 11:32 AMCompletableDeferred
!
It does seem to do the job, like before, but in a better ergonomics. Is there something that I need to be aware of?Dominaezzz
03/13/2021, 11:45 AMleandro
03/13/2021, 11:46 AMmuliyul
03/16/2021, 10:43 AMsuspendCancellableCoroutine
?Dominaezzz
03/16/2021, 12:03 PMmuliyul
03/16/2021, 12:21 PMsuspend fun isSessionValid(): Boolean = suspendCancellableCoroutine { continuation ->
val callback = object : AuthHandler {
override fun onSuccess(session: AuthUserSession) {
continuation.resume(session.isValid)
}
override fun onFailure(e: Exception) {
continuation.resumeWithException(e)
}
}
val auth = builder.setAuthHandler(callback).build()
auth.getSession()
continuation.invokeOnCompletion { auth.release() }
}
Wouldn't that work?Dominaezzz
03/16/2021, 12:31 PMmuliyul
03/16/2021, 12:36 PMJob
instance and effectively achieve the same thing AFAIK.
coroutineContext.getValue(Job).invokeOnCompletion { auth.release() }