源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class CoroutineActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_coroutine)
startCoroutine() }
private fun startCoroutine() { val funTest: suspend CoroutineScope.() -> Unit = { println("funTest") suspendFun1() suspendFun2() }
GlobalScope.launch(Dispatchers.Default, block = funTest) }
suspend fun suspendFun1(){ println("suspendFun1") }
suspend fun suspendFun2(){ println("suspendFun2") } }
|
反编译后的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| public final class CoroutineActivity extends AppCompatActivity { protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(1300001); this.startCoroutine(); }
private final void startCoroutine() { Function2 funTest = (Function2)(new Function2((Continuation)null) { int label;
@Nullable public final Object invokeSuspend(@NotNull Object $result) { Object var3 = IntrinsicsKt.getCOROUTINE_SUSPENDED(); CoroutineActivity var10000; switch(this.label) { case 0: ResultKt.throwOnFailure($result); String var2 = "funTest"; System.out.println(var2); var10000 = CoroutineActivity.this; this.label = 1; if (var10000.suspendFun1(this) == var3) { return var3; } break; case 1: ResultKt.throwOnFailure($result); break; case 2: ResultKt.throwOnFailure($result); return Unit.INSTANCE; default: throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine"); }
var10000 = CoroutineActivity.this; this.label = 2; if (var10000.suspendFun2(this) == var3) { return var3; } else { 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); } }); BuildersKt.launch$default((CoroutineScope)GlobalScope.INSTANCE, (CoroutineContext)Dispatchers.getDefault(), (CoroutineStart)null, funTest, 2, (Object)null); }
@Nullable public final Object suspendFun1(@NotNull Continuation $completion) { String var2 = "suspendFun1"; System.out.println(var2); return Unit.INSTANCE; }
@Nullable public final Object suspendFun2(@NotNull Continuation $completion) { String var2 = "suspendFun2"; System.out.println(var2); return Unit.INSTANCE; } }
|
上述代码:
1、funTest 协程体两个重要方法:
invokeSuspend
create
2、suspendFun1,suspendFun2 方法多了一个 Contination 参数,这也是普通函数无法调起挂机函数的原因