Kotlin协程实用模版合集

目录

✅ Kotlin 协程实用模板合集(适合 Android 项目)

📦 1. 基础挂起函数封装(Repository 层)

⚙️ 2. ViewModel 中使用协程 + 状态处理

⏱️ 3. 带超时控制的挂起操作

🤝 4. 并发请求合并(async 并行执行)

🧱 5. 协程作用域封装(BaseViewModel)

🌐 6. 结合 Retrofit 使用 suspend 接口

🧪 7. 测试中的协程使用:runBlockingTest(Kotlinx Coroutines Test

✅ 总结:协程实用模板覆盖内容


✅ Kotlin 协程实用模板合集(适合 Android 项目)


📦 1. 基础挂起函数封装(Repository 层)

suspend fun fetchUserInfo(userId: String): User {
    delay(1000) // 模拟网络延迟
    return User(userId, "Alice")
}

⚙️ 2. ViewModel 中使用协程 + 状态处理

class UserViewModel(private val repository: UserRepository) : ViewModel() {

    private val _uiState = MutableStateFlow<UiState<User>>(UiState.Loading)
    val uiState: StateFlow<UiState<User>> = _uiState

    fun loadUser(userId: String) {
        viewModelScope.launch {
            try {
                _uiState.value = UiState.Loading
                val user = repository.fetchUserInfo(userId)
                _uiState.value = UiState.Success(user)
            } catch (e: Exception) {
                _uiState.value = UiState.Error(e.message ?: "未知错误")
            }
        }
    }
}

📌 状态封装类: 

sealed class UiState<out T> {
    object Loading : UiState<Nothing>()
    data class Success<T>(val data: T) : UiState<T>()
    data class Error(val message: String) : UiState<Nothing>()
}

⏱️ 3. 带超时控制的挂起操作

suspend fun fetchWithTimeout(): String {
    return withTimeout(3000) {
        delay(2000)
        "结果在3秒内返回"
    }
}

⚠️ 超时会抛出 TimeoutCancellationException,记得 try-catch。


🤝 4. 并发请求合并(async 并行执行)

fun loadDashboardData() {
    viewModelScope.launch {
        try {
            val userDeferred = async { repository.getUser() }
            val postDeferred = async { repository.getUserPosts() }

            val user = userDeferred.await()
            val posts = postDeferred.await()

            _uiState.value = UiState.Success(DashboardData(user, posts))
        } catch (e: Exception) {
            _uiState.value = UiState.Error("加载失败: ${e.message}")
        }
    }
}

📌 优点:多个请求并发执行,整体更快。


🧱 5. 协程作用域封装(BaseViewModel)

open class BaseViewModel : ViewModel() {
    protected fun launchSafe(
        block: suspend CoroutineScope.() -> Unit,
        onError: (Throwable) -> Unit = { it.printStackTrace() }
    ) {
        viewModelScope.launch {
            try {
                block()
            } catch (e: Throwable) {
                onError(e)
            }
        }
    }
}

使用示例: 

launchSafe({
    val user = repository.getUser()
    _uiState.value = UiState.Success(user)
}, {
    _uiState.value = UiState.Error("请求失败: ${it.message}")
})

🌐 6. 结合 Retrofit 使用 suspend 接口

interface ApiService {
    @GET("user/{id}")
    suspend fun getUser(@Path("id") id: String): User
}

配合 Retrofit 初始化: 

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

val api = retrofit.create(ApiService::class.java)

然后就可以直接在协程中使用: 

val user = api.getUser("123")

🧪 7. 测试中的协程使用:runBlockingTest(Kotlinx Coroutines Test

@Test
fun testFetchUser() = runTest {
    val user = repository.fetchUserInfo("123")
    assertEquals("Alice", user.name)
}

需要依赖: 

testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")

✅ 总结:协程实用模板覆盖内容

模板场景
✅ Repository 封装挂起函数网络/数据库请求
✅ ViewModel 中的协程控制生命周期绑定、状态管理
✅ 异常处理封装避免崩溃,优雅处理错误
✅ 超时机制防止请求卡死
✅ 并发请求合并提高加载效率
✅ 协程作用域封装通用的 launchSafe 模板
✅ Retrofit + suspend 接口实战开发标准写法
✅ 单元测试使用协程保证逻辑正确性
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王景程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值