Retrofit
返回 Flow<out T>
Dependency | Version |
---|---|
kotlin | 1.5.21 |
kotlinx-coroutines-android | 1.5.1 |
retrofit | 2.9.0 |
1.root build.gradle
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
2.app build.gradle
dependencies {
implementation 'com.github.chenxyu:retrofit-adapter-flow:1.2.0'
}
@POST(API.LOGIN)
fun login(@Body any: Any): Flow<User>
Retrofit.Builder()
...
.addCallAdapterFactory(FlowCallAdapterFactory.create())
.build()
lifecycleScope.launch(Dispatchers.Main) {
githubService.search("kotlinx.coroutines")
.flowOn(Dispatchers.IO)
.catch { e ->
if (e is CancellationException) {
Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_LONG).show()
}
}.collect {
textView.text = it
}
}