Hello Coroutine

2021-11-09  本文已影响0人  hgwxr

Hello Coroutine

什么是协程

协程作用(个人见解)

Kotlin中的协程

@SinceKotlin("1.3")
public interface CoroutineContext {
    public operator fun <E : Element> get(key: Key<E>): E?
    public fun <R> fold(initial: R, operation: (R, Element) -> R): R
    public operator fun plus(context: CoroutineContext): CoroutineContext =
        if (context === EmptyCoroutineContext) this else 
            context.fold(this) { acc, element ->
                val removed = acc.minusKey(element.key)
                if (removed === EmptyCoroutineContext) element else {
                    val interceptor = removed[ContinuationInterceptor]
                    if (interceptor == null) CombinedContext(removed, element) else {
                        val left = removed.minusKey(ContinuationInterceptor)
                        if (left === EmptyCoroutineContext) CombinedContext(element, interceptor) else
                            CombinedContext(CombinedContext(left, element), interceptor)
                    }
                }
            }
    public fun minusKey(key: Key<*>): CoroutineContext
    public interface Key<E : Element>
    public interface Element : CoroutineContext {
        public val key: Key<*>
        public override operator fun <E : Element> get(key: Key<E>): E? =
            @Suppress("UNCHECKED_CAST")
            if (this.key == key) this as E else null
        public override fun <R> fold(initial: R, operation: (R, Element) -> R): R =
            operation(initial, this)
        public override fun minusKey(key: Key<*>): CoroutineContext =
            if (this.key == key) EmptyCoroutineContext else this
    }
}
img
val job = launch {
    println("test job")
}
class CoroutinesSample {
    fun login(username:String,pad:String,callback:(token:String)->Unit){
        try {
            TimeUnit.SECONDS.sleep(1)
        }catch (e:Exception){
            e.printStackTrace()
        }
        callback("default token")
    }
    fun getUserInfo(token:String,callback:(userName:String)->Unit){
        try {
            TimeUnit.SECONDS.sleep(1)
        }catch (e:Exception){
            e.printStackTrace()
        }
        callback("user name hgwxr")
    }
}
fun main(args: Array<String>) {
    val sample = CoroutinesSample()
    sample.apply {
        login("hgwxr","psd") {token ->
            println("received  token")
            getUserInfo(token){userName ->
                println("received  user name: $userName")
            }
        }
    }
}
received  token:default token
received  user name: user name hgwxr

Process finished with exit code 0
suspend fun getUserInfo2Coroutines(token: String): String {
        return suspendCoroutine {
            getUserInfo(token) { userName ->
                it.resume(userName)
            }
        }
    }

suspend fun login2Coroutines(username: String, psd: String): String {
        return suspendCoroutine {
            login(username, psd) { token ->
                it.resume(token)
            }
        }
    }
 suspend fun loginCoroutines(username: String, pad: String): String {
        return coroutineScope {
            delay(1000L)
            "default token"
        }
    }

    suspend fun getUserInfoCoroutines(token: String): String {
        return coroutineScope {
            delay(1000L)
            "user name hgwxr"
        }
    }
fun main(args: Array<String>) {
    //
    val sample = CoroutinesSample()
    sample.apply {
        runBlocking {
            val token = login2Coroutines("hgwxr", "psd")
            println("received  token:$token")
            val userName = getUserInfo2Coroutines(token)
            println("received  user name: $userName")
        }
    }
}
1971636467456_.pic_hd.jpg
* ```java
  public static final void main(@NotNull String[] args) {
        Intrinsics.checkNotNullParameter(args, "args");
        BuildersKt.runBlocking$default((CoroutineContext)null, (Function2)(new Function2((Continuation)null) {
           int label;
  
           @Nullable
           public final Object invokeSuspend(@NotNull Object $result) {
              Object var4 = IntrinsicsKt.getCOROUTINE_SUSPENDED();
              Object var10000;
              switch(this.label) {
              case 0:
                 ResultKt.throwOnFailure($result);
                 this.label = 1;
                 var10000 = CoroutinesSample3Kt.fun3(this);
                 if (var10000 == var4) {
                    return var4;
                 }
                 break;
              case 1:
                 ResultKt.throwOnFailure($result);
                 var10000 = $result;
                 break;
              default:
                 throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
              }
  
              String res = (String)var10000;
              boolean var3 = false;
              System.out.println(res);
              return Unit.INSTANCE;
           }
  
           @NotNull
           public final Continuation create(@Nullable Object value, @NotNull Continuation completion) {
              Intrinsics.checkNotNullParameter(completion, "completion");
              Function2 var3 = new <anonymous constructor>(completion);
              return var3;
           }
  
           public final Object invoke(Object var1, Object var2) {
              return ((<undefinedtype>)this.create(var1, (Continuation)var2)).invokeSuspend(Unit.INSTANCE);
           }
        }), 1, (Object)null);
     }
  ```

其他知识点

异常处理,异常取消、超时,mutext,actor,channel等

Java实现协程

https://github.com/kilim/kilim

https://github.com/offbynull/coroutines

https://github.com/puniverse/quasar

上一篇下一篇

猜你喜欢

热点阅读