how to break from lambda passed to recursive function when provided condition met

我的梦境 提交于 2019-12-02 08:32:58

It can be done for example with throwing a lightweight exception. You have to declare custom exception:

class LoopStopException : Throwable("Stop look", null, false, false) // lightweight throwable without the stack trace

and catch it in loopWithoutDelay:

private suspend fun loopWithoutDelay(block: suspend () -> Unit) {
    try {
        while (true) {
            block()
        }
    } catch (e: LoopStopException) {
        //do nothing
    }
}

I didn't understand much about the function delayedResult, because none of the dsl's public functions return a result. However, I come up with an solution for cancelling the loop.

As far as I understood, we have to have a loop that doesn't block the current thread. Therefore, it must be run in a coroutine, but in order to be able to cancel the loop, the dsl must run its own coroutine. This inner coroutine is run using coroutineScope, so it suspends the parent coroutine until it's finished or cancelled.

@ExperimentalTime
class Loop {
    private val loopInterval = 1.seconds

    suspend fun loop(block: suspend () -> Unit) = loop(loopInterval, block)

    suspend fun loop(minimumInterval: Duration, block: suspend () -> Unit):Job  = coroutineScope {
        launch {
            while (true) {
                block()
                delay(minOf(minimumInterval, loopInterval).toLongMilliseconds())
            }
        }
    }

    suspend fun stopIf(condition: Boolean) = coroutineScope {
        suspendCancellableCoroutine<Unit> {
            if (condition) it.cancel() else it.resumeWith(Result.success(Unit))
        }
    }
}

@ExperimentalTime
suspend fun loop(block: suspend Loop.() -> Unit):Job {
    return Loop().run {
        this.loop {
            block(this)
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!