Last active
September 5, 2023 19:10
-
-
Save gpeal/b77509b46bd6d1db557b952731d01101 to your computer and use it in GitHub Desktop.
Conflated Job
This file contains hidden or 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
class MyClass(private val scope: CoroutineScope) { | |
private val job = ConflatedJob() | |
fun retry() { | |
retryJob += scope.launch { | |
delay(Long.MAX_VALUE) | |
} | |
} | |
} | |
/** | |
* Job container that will cancel the previous job if a new one is set. | |
* | |
* Assign the new job with the += operator. | |
*/ | |
class ConflatedJob { | |
private var job: Job? = null | |
private var prevJob: Job? = null | |
val isActive get() = job?.isActive ?: false | |
@Synchronized | |
operator fun plusAssign(newJob: Job) { | |
cancel() | |
job = newJob | |
} | |
fun cancel() { | |
job?.cancel() | |
prevJob = job | |
} | |
fun start() { | |
job?.start() | |
} | |
/** | |
* This can be used inside newly started job to await completion of previous job. | |
*/ | |
suspend fun joinPreviousJob() { | |
val thisJob = coroutineContext[Job] | |
val jobToJoin = synchronized(this) { if (job == thisJob) prevJob else job } | |
jobToJoin?.join() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment