Kotlin Flow 实战:用数据流管道告别回调地狱
你写过这样的代码吗?
// 监听用户输入 → 请求搜索建议 → 过滤结果 → 更新 UI
searchBox.addTextChangedListener { text ->
api.searchSuggestions(text.toString()) { result ->
if (result.isSuccessful) {
val filtered = result.body()?.filter { it.isNotEmpty() }
if (filtered != null) {
runOnUiThread {
adapter.submitList(filtered)
}
}
}
}
}
回调套回调,if 嵌 if——经典的"回调地狱"。更头疼的是,你还得手动处理防抖、取消请求、异常恢复……代码越写越像一团乱麻。
Kotlin 的 Flow(数据流) 就是来终结这种痛苦的。它让你像搭流水线一样,把异步数据一个操作符接一个操作符地串起来,代码从上到下读,逻辑清晰得像白开水。