Skip to content

Instantly share code, notes, and snippets.

@gpeal

gpeal/ConflatedJob.kt

Last active Apr 23, 2021
Embed
What would you like to do?
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