kotlin coroutines 协程教程(四) Suspend function 挂起函数

kotlin coroutines 协程教程(四) Suspend function 挂起函数

Suspend function 挂起函数,的分析,基于 Coroutine 1.3 版本的源码。

简单用法

一个简单的例子如下:

fun test1() {
    GlobalScope.launch {
        val arg1 = sunpendF1()
        var arg2 = sunpendF2()
        doLog("suspend finish arg1:$arg1  arg2:$arg2  result:${arg1 + arg2}")
    }
}

private suspend fun sunpendF1(): Int {
    delay(1000)
    doLog("suspend fun 1")
    return 2
}

private suspend fun sunpendF2(): Int {
    delay(1000)
    doLog("suspend fun 2")
    return 4
}

最终控制台的输入结果如下:

01-07 19:21:49.626 9616-10074/com.yy.yylite.kotlinshare I/suspend: suspend fun 1
01-07 19:21:50.633 9616-10074/com.yy.yylite.kotlinshare I/suspend: suspend fun 2
    suspend finish arg1:2  arg2:4  result:6

也就是说,最后的输出依赖,sunpendF1() sunpendF2,只有等两个函数都做完了,才会输出,但是挂起并不是阻塞。

Suspend 挂起函数原理

挂起函数,并不会阻塞线程,这里的实现原理背后是 kotlin 进行了巧妙的编译层次的设计,通常来说一个挂起函数如下:

suspend fun test1() {
    KLog.i("test1") { "test1" }
    val homeItemInfo = HomeItemInfo()
    homeItemInfo.adId = "89"
    delay(100)
    KLog.i("test1") { "test1-end" }
}

我们使用 tools->show kotlin bytecode->decompile 查看 转化为 java 实现代码如下:

public final Object test1(@NotNull Continuation var1) {
   Object $continuation;
   label28: {
      if (var1 instanceof ) {
         $continuation = ()var1;
         if (((()$continuation).getLabel() & Integer.MIN_VALUE) != 0) {
            (()$continuation).setLabel((()$continuation).getLabel() - Integer.MIN_VALUE);
            break label28;
         }
      }

      $continuation = new CoroutineImpl(var1) {
         // $FF: synthetic field
         Object data;
         // $FF: synthetic field
         Throwable exception;
         Object L$0;
         Object L$1;

         @Nullable
         public final Object doResume(@Nullable Object data, @Nullable Throwable throwable) {
            this.data = data;
            this.exception = throwable;
            super.label |= Integer.MIN_VALUE;
            return SuspendTest.this.test1(this);
         }

         // $FF: synthetic method
         final int getLabel() {
            return super.label;
         }

         // $FF: synthetic method
         final void setLabel(int var1) {
            super.label = var1;
         }
      };
   }

   Object var3 = (()$continuation).data;
   Throwable var4 = (()$continuation).exception;
   Object var6 = IntrinsicsKt.getCOROUTINE_SUSPENDED();
   HomeItemInfo homeItemInfo;
   switch((()$continuation).getLabel()) {
   case 0:
      if (var4 != null) {
         throw var4;
      }

      KLog.INSTANCE.i("test1", (Function0)null.INSTANCE);
      homeItemInfo = new HomeItemInfo();
      homeItemInfo.adId = "89";
      (()$continuation).L$0 = this;
      (()$continuation).L$1 = homeItemInfo;
      (()$continuation).setLabel(1);
      if (DelayKt.delay(100, (Continuation)$continuation) == var6) {
         return var6;
      }
      break;
   case 1:
      homeItemInfo = (HomeItemInfo)(()$continuation).L$1;
      SuspendTest var7 = (SuspendTest)(()$continuation).L$0;
      if (var4 != null) {
         throw var4;
      }
      break;
   default:
      throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
   }

   KLog.INSTANCE.i("test1", (Function0)null.INSTANCE);
   return Unit.INSTANCE;
}

首先来看函数签名,这里会变成传入一个参数 Continuation,这个是 kotlin 中实现挂起的接口,其源码定义如下,也就是最终挂起函数的逻辑,是通过这个 resumeWith() 分发的。

public interface Continuation {
    /**
     * Context of the coroutine that corresponds to this continuation.
     */
    // todo: shall we provide default impl with EmptyCoroutineContext?
    public val context: CoroutineContext

    /**
     * Resumes the execution of the corresponding coroutine passing successful or failed [result] as the
     * return value of the last suspension point.
     */
    public fun resumeWith(result: Result)
}

所以实际上 挂起函数在编译器的封装下,变成了一个 Continuation。通过字节码工具,我们可以看到:

kotlinx/coroutines/Deferred.delay (Lkotlin/coroutines/Continuation;)Ljava/lang/Object;

实际上这是一个 Continuation 对象。

所以实际上其流程等于:

kotlin coroutines 协程教程(四) Suspend function 挂起函数_第1张图片
image

你可能感兴趣的:(kotlin coroutines 协程教程(四) Suspend function 挂起函数)