Pat Teruel
03/10/2023, 9:28 PMGlobalScope.asyncDispatchQueue.global().asyncimport kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
class AsyncSchedulerCaller(
    delayTime: Long,
    suspendFunction: suspend () -> Unit
) {
    init {
        GlobalScope.async {
            delay(delayTime)
            if (invalidated) {
                println("Invalidated.")
            } else {
                isRunning = true
                suspendFunction()
                isRunning = false
            }
        }
    }
    var invalidated = false
    var isRunning = false
    fun invalidate() {
        invalidated = true
    }
}class SomeClass { 
    var scheduler: AsyncSchedulerCaller? = null 
    suspend fun someSuspendFunction() { 
        runSomeApiCallHere() 
        scheduler?.invalidate() // this will make sure that the existing scheduled task will not be run
        scheduler = AsyncSchedulerCaller( 
            delayTime = 500, // will run after 500 milliseconds
            suspendFunction = {
                runSomeOtherApiCallHere() 
            }
        )
    }
}Jeff Lockhart
03/11/2023, 7:01 PMGlobalScope.asyncGlobalScope.launchDispatchQueue.global().asyncclass AsyncSchedulerCaller(
    delayTime: Long,
    suspendFunction: suspend () -> Unit
) {
    private val job = GlobalScope.launch {
        delay(delayTime)
        isRunning = true
        suspendFunction()
        isRunning = false
    }
    var isRunning = false
        private set
    fun invalidate() {
        job.cancel()
        println("Invalidated.")
    }
}invalidate()class AsyncSchedulerCaller(
    delayTime: Long,
    scope: CoroutineScope,
    suspendFunction: suspend () -> Unit
) {
    private val job = scope.launch {
        try {
            delay(delayTime)
        } catch (e: CancellationException) {
            println("Invalidated.")
            throw e
        }
        isRunning = true
        suspendFunction()
        isRunning = false
    }
    var isRunning = false
        private set
}CoroutineScopeBig Chungus
03/11/2023, 10:21 PMPat Teruel
03/13/2023, 1:35 AMasyncJeff Lockhart
03/13/2023, 5:10 AMsuspendFunction()CancellationExceptiondelay()CancellationExceptionPat Teruel
03/14/2023, 1:54 AMsuspend fun a() {
    b()
}
suspend fun b() {
    delay(1000)
}a()b()a()b()b()b()suspend fun a() {
   existingCaller?.invalidate()
   existingCaller = AsyncCaller {
        b()
   } 
}#Native
kotlin.native.binary.objcExportSuspendFunctionLaunchThreadRestriction=noneJeff Lockhart
03/14/2023, 6:00 AMkotlin.native.binary.memoryModel=experimentalkotlin.native.binary.objcExportSuspendFunctionLaunchThreadRestriction=none