Skip to content

Instantly share code, notes, and snippets.

@gpeal
Last active September 5, 2023 19:10
Show Gist options
  • Save gpeal/b77509b46bd6d1db557b952731d01101 to your computer and use it in GitHub Desktop.
Save gpeal/b77509b46bd6d1db557b952731d01101 to your computer and use it in GitHub Desktop.
Conflated Job
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