kotlin coroutines 協(xié)程教程(四) Suspend function 掛起函數(shù)

kotlin coroutines 協(xié)程教程(四) Suspend function 掛起函數(shù)

Suspend function 掛起函數(shù),的分析,基于 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
}

最終控制臺的輸入結(jié)果如下:

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,只有等兩個函數(shù)都做完了,才會輸出,但是掛起并不是阻塞。

Suspend 掛起函數(shù)原理

掛起函數(shù),并不會阻塞線程,這里的實現(xiàn)原理背后是 kotlin 進行了巧妙的編譯層次的設(shè)計,通常來說一個掛起函數(shù)如下:

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 查看 轉(zhuǎn)化為 java 實現(xiàn)代碼如下:

public final Object test1(@NotNull Continuation var1) {
   Object $continuation;
   label28: {
      if (var1 instanceof <undefinedtype>) {
         $continuation = (<undefinedtype>)var1;
         if ((((<undefinedtype>)$continuation).getLabel() & Integer.MIN_VALUE) != 0) {
            ((<undefinedtype>)$continuation).setLabel(((<undefinedtype>)$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 = ((<undefinedtype>)$continuation).data;
   Throwable var4 = ((<undefinedtype>)$continuation).exception;
   Object var6 = IntrinsicsKt.getCOROUTINE_SUSPENDED();
   HomeItemInfo homeItemInfo;
   switch(((<undefinedtype>)$continuation).getLabel()) {
   case 0:
      if (var4 != null) {
         throw var4;
      }

      KLog.INSTANCE.i("test1", (Function0)null.INSTANCE);
      homeItemInfo = new HomeItemInfo();
      homeItemInfo.adId = "89";
      ((<undefinedtype>)$continuation).L$0 = this;
      ((<undefinedtype>)$continuation).L$1 = homeItemInfo;
      ((<undefinedtype>)$continuation).setLabel(1);
      if (DelayKt.delay(100, (Continuation)$continuation) == var6) {
         return var6;
      }
      break;
   case 1:
      homeItemInfo = (HomeItemInfo)((<undefinedtype>)$continuation).L$1;
      SuspendTest var7 = (SuspendTest)((<undefinedtype>)$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;
}

首先來看函數(shù)簽名,這里會變成傳入一個參數(shù) Continuation,這個是 kotlin 中實現(xiàn)掛起的接口,其源碼定義如下,也就是最終掛起函數(shù)的邏輯,是通過這個 resumeWith() 分發(fā)的。

public interface Continuation<in T> {
    /**
     * 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<T>)
}

所以實際上 掛起函數(shù)在編譯器的封裝下,變成了一個 Continuation。通過字節(jié)碼工具,我們可以看到:

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

實際上這是一個 Continuation 對象。

所以實際上其流程等于:

image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容