目录

✅ 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 接口 实战开发标准写法
✅ 单元测试使用协程 保证逻辑正确性
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐