Kotlin Coroutine 範例

Teng Wang
3 min readJul 23, 2020

--

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了。

Photo by Thomas Tucker on Unsplash

註1:Sample code不能run的話,以下兩種方式:

  1. 自己改一改Gradle 等等的環境參數,可能是環境設定問題。
  2. 星期三晚上到台北天瓏書局二樓,大聲呼喊:Teng他媽寫這甚麼爛Code,給我滾出來受死!

— 通常Android讀書會會在那邊舉辦 codeclub。

--

--

Teng Wang
Teng Wang

Written by Teng Wang

A Software Research & Development

No responses yet