温馨提示:本文最后更新于
2025-12-17 17:42:13,某些文章具有时效性,若有错误或已失效,请在下方留言。Retrofit 是 Square 出品的一个 类型安全的 HTTP 客户端,用于 Android / Java / Kotlin 中进行网络请求。
- 基于 OkHttp
- 支持 协程(suspend)
- 支持 Gson / Moshi 解析
基本使用
1. 添加依赖
dependencies {
implementation("com.squareup.retrofit2:retrofit:3.0.0")
implementation("com.squareup.retrofit2:converter-gson:3.0.0")
2. 定义数据模型
data class Post(
val id: Int,
val title: String,
val body: String
)
3. 定义 API 接口
interface ApiService {
@GET("posts")
suspend fun getPosts(): List<Post>
}
常见的注解有
@GET、@POST、@PUT、@DELETE@Path@Query@Body
4. 创建 Retrofit 实例
object RetrofitInstance {
// BASE URL
private const val BASE_URL = "https://jsonplaceholder.typicode.com/"
// by lazy 将属性的初始化延迟到第一次被访问时才执行。
val api: ApiService by lazy {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
retrofit.create(ApiService::class.java)
}
}
5. 在 Repository 中调用
/**
* Repository:
* 充当数据源(网络 API 等)与 ViewModel 之间的中介层,负责协调和提供数据。
*/
class PostRepository {
private val apiService = RetrofitInstance.api
suspend fun getPosts(): List<Post> {
return apiService.getPosts()
}
}
6. 在 ViewModel 中使用
class PostViewModel : ViewModel() {
private val repository = PostRepository()
/**
* ViewModel 使用 mutableStateOf<List<Post>> 而不是 LiveData,
* 从而直接由 Compose 进行状态管理和 UI 更新,无需额外的状态转换
*/
var posts by mutableStateOf<List<Post>>(emptyList())
private set
/**
* init 是 类的初始化代码块,会在 ViewModel 被创建时立即执行。
* - 在 构造函数执行完成后自动调用
* - 每个 ViewModel 只执行一次
* - 常用于
* - 初始化数据
* - 触发首次加载(如网络请求)
*
*/
init {
/**
* 在 ViewModel 生命周期内,启动一个协程来执行耗时操作(如网络请求),并在 ViewModel 销毁时自动取消。
*/
viewModelScope.launch {
// 获取网络数据
var fetchedPosts = repository.getPosts()
// 更新状态
// 对 posts 的任何更新,都会触发所有读取该状态的 Composable 重新组合(recomposition)。
posts = fetchedPosts
}
}
}
© 版权声明
THE END













暂无评论内容