fun postItem(item: Item) {
launch (CommonPool) { //显性协程上下文
val taken = preparePost()
val post - submitPost(token, item)
processPost(post)
}
}
suspend fun preparePost() : Token {
return suspendCoroutine {//....}
}
编译器会怎么做?
suspend fun submitPost(token: Token, item: Item) {
//...
}
//编译后
Object submitPost(Token token, Item item, Continuation<Post> cont){
//...
}
publicinterfaceContinuation<inT>{public val context: CoroutineContext
public fun resume(value: T)
public fun resumeWithException(ex: Throwable)
}
//内部状态机
switch (cont.label){
case0:
cont.label = 1;
preparePost(cont)
break;
case1:
Token token = (Token) prevResult;
cont.label = 2;
submitPost(token, item, cont);
case2:
Post post = (Post) prevResult;
processPost(post);
}
特别轻量
//main()是协程实现的
fun main(args: Array<String>) = runBlocking {
val jobs = List(100000){ //100000个
launch(CommonPool) {
delay(1000) //在延迟1秒内启动别的协程
}
}
jobs.forEach { it.join() }
}
//launch和async的区别在于后者有返回值
fun doSth() = async(CommonPool) {
//...
}
val request = doSth()
request.wait()
await
val str = await(work()) //String result//work()的返回值是CompletableFuture<String>
suspend fun <T> await(f: CompletableFuture<T>): T{
suspendCoroutine { c ->
f.whenComplete { value, ex ->
if (ex != null) c.resumeWithException(ex)
else c.resume(value)
}
}
}
通讯和同步
Job:一个可完成和可取消的实体,用于代表一个协程
deferred:一个Future用于,suspend函数的await()
Mutex:with suspend fun lock
Channel:SendChannel 和 ReceiveChannel
RendezvousChannel:同步的集合地
ArrayChannel:固定大小的Buffer
LinkedListChannel:无限制
ConflatedChannel:只有最近的被发送的元素会被保留
BroadCastChannel:可以被多个订阅,都能收到
协程建造器
launch
async
future
runBlocking
actor/produce: 通过Channel消费生产消息
publish
rxCompletable, rxSingle, rxObservable, rxFlowable
其他
顶层函数
select:支持CSP风格的编程
delay:延迟一定时间
await:
public suspend fun <T> java.util.concurrent.CompletableFuture<T>.await(): T { /* compiled code */ }
public suspend fun <T> java.util.concurrent.CompletionStage<T>.await(): T { /* compiled code */ }