我正在尝试构建CharSequence的可中断版本。遵循以下原则:
class InterruptableCharSequence(private val delegate: CharSequence) : CharSequence {
override fun get(index: Int): Char = runBlocking {
yield() // Suspend here, in case we have cancelled
delegate[index]
}
override fun subSequence(start: Int, end: Int): CharSequence {
return delegate.subSequence(start, end)
}
override fun toString(): String {
return delegate.toString()
}
}
由于这是在实现现有接口,因此我无法使get
成为暂停函数,但是我想从一个协同例程(几个层次)中调用它并能够中断/取消它。我将如何实现这一目标?有什么方法可以避免这种阻塞或为每个字符创建新的协程吗?