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 <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;
}
首先來看函數簽名,這里會變成傳入一個參數 Continuation,這個是 kotlin 中實現掛起的接口,其源碼定義如下,也就是最終掛起函數的邏輯,是通過這個 resumeWith() 分發的。
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>)
}
所以實際上 掛起函數在編譯器的封裝下,變成了一個 Continuation。通過字節碼工具,我們可以看到:
kotlinx/coroutines/Deferred.delay (Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
實際上這是一個 Continuation 對象。
所以實際上其流程等于:
image