Luis Munoz
05/20/2020, 2:49 PM/**
* 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.
*/
@SinceKotlin("1.3")
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.BINARY)
public annotation class RestrictsSuspension
streetsofboston
05/20/2020, 3:03 PMCasey Brooks
05/20/2020, 3:08 PMsuspend
to implement the yield()
function. Sequences wouldn’t be able to be used synchronously if you could jump to other threads during their sequence { }
block, so the suspension is restricted so that only suspend functions defined on SequenceScope
can be called.streetsofboston
05/20/2020, 3:09 PMSequences
with their yield
function.
Another example is to unwrap a contained value from its container in an imperative way, E.g. instead of
val result: Either<Error, MyData> = repo.getResult()
result.flatMap { repo.getOtherEitherResult(it) }
you could do
<http://Either.do|Either.do> {
val result: MyData = repo.getResut().bind()
repo.getOtherEitherResult(result).bind()
}
^^^ the lambda of do
has a receiver of a type ‘scope’ that is marked with this annotation and bind()
is defined on that same ‘scope’ (to return the value of the flatMap
). You want to prevent the developer from calling delay
or other `suspend fun`s not defined on that ‘scope’.Luis Munoz
05/20/2020, 3:16 PMstreetsofboston
05/20/2020, 3:33 PMsuspend
is just used for cooperative ‘single’-threading, allowing for ‘goto’ like behavior jumping into and out of other functions. If this restriction is not necessary, then you won’t need this annotation.
If you want suspend-and-resume type of behavior in your interface/class’ methods and you’d like to fully control the suspend-and-resume type of behavior throughout your API (eg disallow asynchronous calls), then this annotation will help you.Luis Munoz
05/20/2020, 3:49 PM