- 如果我不想了解Coroutine — Kotlin Coroutine 那一兩件事情
- 如果我不想了解協程用起來的體驗 — 用 Retrofit 與 Coroutines 實作 HTTP Request
- 我也不想知道Coroutines的基礎 — Kotlin coroutine 基礎筆記
Check it out.
Sample code在這 [註1]
這個範例是利用Github的API + Retrofit寫的範例,有人不懂Retrofit的話,
留言區留言,需要的人多再寫。
class MainActivity : AppCompatActivity() {
lateinit var mGithubService: GithubService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// retrofit 設定
mGithubService = GithubServiceHelper.getGithubService
(BuildConfig.GITHUTAPI_URI) // 宣告CoroutineScope
CoroutineScope(Dispatchers.IO).launch {
// 執行 api,等 api response
// Retrofit return Differed<List<GithubUserItem>>
val result = mGithubService.allUsers.await() // 程式跑完上面那行,result就已經取回api response了 // Switch to Android mainThread
withContext(Dispatchers.Main) {
// 抓到第一筆GithubUserItem的名稱放到 textView裡面
textView.text = result[0].login.toString()
}
}
}
}
你學會coroutine了。
註1:Sample code不能run的話,以下兩種方式:
- 自己改一改Gradle 等等的環境參數,可能是環境設定問題。
- 星期三晚上到台北天瓏書局二樓,大聲呼喊:Teng他媽寫這甚麼爛Code,給我滾出來受死!
— 通常Android讀書會會在那邊舉辦 codeclub。