美文网首页
Kotlin协程的@RestrictsSuspension注解

Kotlin协程的@RestrictsSuspension注解

作者: 一起来看雷阵雨 | 来源:发表于2020-04-06 17:00 被阅读0次

Classes and interfaces marked with this annotation are restricted when used as receivers for >extension
suspend functions. These suspend extensions can only invoke other member or extension >suspend functions on this particular
receiver and are restricted from calling arbitrary suspension functions

简单来说,如果一个接口或者类被标注@RestrictsSuspension,那么当这个类作为suspend扩展函数接受者的时候,其suspend函数内部不能调用其它CoroutineScope的suspend函数。

suspend fun SequenceScope<String>.test(block: suspend GlobalScope.() -> Int){
    block()
}

报错:Restricted suspending functions can only invoke member or extension 
suspending functions on their restricted coroutine scope

上面的代码,在SequenceScope的test扩展函数中调用了GlobalScope的扩展lambda--block;而SequenceScope正是被@RestrictsSuspension注解修饰。所以编译器会报错!

@RestrictsSuspension
@SinceKotlin("1.3")
public abstract class SequenceScope<in T> internal constructor(){。。。}

相关文章

网友评论

      本文标题:Kotlin协程的@RestrictsSuspension注解

      本文链接:https://www.haomeiwen.com/subject/qtvbphtx.html