Last active
November 14, 2021 19:32
-
-
Save lgtout/c0820e2eabc8ec652d2fa2a343abb891 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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