Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lgtout/c0820e2eabc8ec652d2fa2a343abb891 to your computer and use it in GitHub Desktop.
Save lgtout/c0820e2eabc8ec652d2fa2a343abb891 to your computer and use it in GitHub Desktop.
fun resolveDeepLink(
lifecycleScope: LifecycleCoroutineScope,
lifecycle: Lifecycle,
handler: DefaultScreenDeepLinkHandler,
provider: String,
json: JSONObject,
) {
val cancellable = cancelOnLifecycleStopAndRetryOnStartApiCallbackTask<Boolean>(
lifecycle, lifecycleScope, {
// Do something with result
}) { handler.resolveDeepLink(provider, json, it) }
cancellable.cancel()
}
interface Cancellable {
fun cancel()
}
class CancelOnLifecycleStopAndRetryOnStartApiCallbackTask<T> private constructor (
private val lifecycle: Lifecycle,
private val coroutineScope: CoroutineScope,
callback: (T) -> Unit,
private val api: suspend ((T) -> Unit) -> Unit
) : DefaultLifecycleObserver, Cancellable {
private var job: Job? = null
private var result: T? = null
private val update = { t: T ->
t.also {
result = it
removeObserver()
}
}.andThen(callback)
private fun resolveDeepLink() {
job = coroutineScope.launch {
api(update)
}
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
resetJob()
}
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
if (job == null) resolveDeepLink()
}
private fun removeObserver() = lifecycle.removeObserver(this)
override fun cancel() {
if (result != null) return
resetJob()
removeObserver()
}
private fun resetJob() {
job?.cancel()
job = null
}
companion object {
fun <T> cancelOnLifecycleStopAndRetryOnStartApiCallbackTask(
lifecycle: Lifecycle,
coroutineScope: CoroutineScope,
callback: (T) -> Unit,
api: suspend ((T) -> Unit) -> Unit
): Cancellable {
val task = CancelOnLifecycleStopAndRetryOnStartApiCallbackTask(
lifecycle,
coroutineScope,
callback,
api)
lifecycle.addObserver(task)
return task
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment