Kotlin + 协程 + Retrofit + MVVM优雅的实现网络请求
时间: 2023-09-24 11:06:53 浏览: 110
Android-kotlin实现网络请求库
当然,我很愿意回答您的问题。下面是一个 Kotlin + 协程 + Retrofit + MVVM 实现网络请求的示例:
1. 在 build.gradle 中添加以下依赖:
```
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
implementation 'com.squareup.retrofit2:retrofit:2.8.1'
implementation 'com.squareup.retrofit2:converter-gson:2.8.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
```
2. 创建 Retrofit 接口:
```kotlin
interface ApiService {
@GET("users/{user}/repos")
suspend fun getRepos(@Path("user") user: String): List<Repo>
}
```
3. 创建数据模型:
```kotlin
data class Repo(val name: String)
```
4. 创建 Repository:
```kotlin
class MainRepository(private val apiService: ApiService) {
suspend fun getRepos(user: String): List<Repo> {
return apiService.getRepos(user)
}
}
```
5. 创建 ViewModel:
```kotlin
class MainViewModel(private val repository: MainRepository) : ViewModel() {
private val _repos = MutableLiveData<List<Repo>>()
val repos: LiveData<List<Repo>> = _repos
fun getRepos(user: String) {
viewModelScope.launch {
_repos.value = repository.getRepos(user)
}
}
}
```
6. 创建 Activity/Fragment:
```kotlin
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val apiService = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
val repository = MainRepository(apiService)
viewModel = ViewModelProvider(this, MainViewModelFactory(repository))[MainViewModel::class.java]
viewModel.repos.observe(this, Observer { repos ->
// do something with repos
})
viewModel.getRepos("octocat")
}
}
```
以上就是一个使用 Kotlin + 协程 + Retrofit + MVVM 实现网络请求的示例。希望对您有所帮助!
阅读全文