标准函数 suspendCoroutine

Kotlin协程标准函数实现:

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
suspend fun requestGit() : String {
return suspendCoroutine<String> { coroutineContext ->
thread {
val callFactory: Call.Factory = OkHttpClient()
val request = Request.Builder()
.url("https://api.github.com/user")
.get()
.build()
try {
val call = callFactory.newCall(request)
val response = call.execute()
val result = response.body?.string()
/**
                 * 成功的回调
                 */
coroutineContext.resume(result ?: "")
} catch (t: Throwable) {
                /**
                 * 失败的回调
                 */
coroutineContext.resumeWithException(t)
}
}
}
}

suspend“分饰两角”:声明函数类型时充当async的作用,调用时充当await的作用。