Architecture Pitfall: Why Your Repository Should Never Launch Coroutines
Repositories should not launch coroutines because doing so leaks concurrency control into the data layer and breaks separation of concerns.
重點摘要
Launching coroutines in repositories violates separation of concerns.
It obscures lifecycle, cancellation and threading control, harming testability.
Prefer exposing suspend functions, Flow, or letting callers manage coroutine scopes.
The article argues that repositories should never launch coroutines because that moves concurrency and execution decisions into the data layer and breaks separation of concerns. Starting coroutines inside repositories hides where work is dispatched and controlled, complicating lifecycle management, cancellation, error propagation, and unit testing, while increasing the risk of threading-related bugs. Instead, the author recommends keeping coroutine launching at higher layers or designing repository APIs that expose suspend functions, Kotlin Flow, or accept a caller-provided CoroutineScope or dispatcher. By letting callers or higher-level components manage dispatchers and scope lifetimes, applications gain clearer boundaries, easier testing, predictable lifecycle behavior, and simpler error handling. The piece frames avoiding repository-side coroutine launches as an important architectural best practice.
架构陷阱:为什么你的 Repository 绝不应启动协程
Repository 不应启动协程,因为这会将并发控制泄漏到数据层,破坏关注点分离并增加测试与生命周期管理难度。
重點摘要
在 Repository 中启动协程会违反关注点分离。
会隐藏执行与取消的控制,增加测试与生命周期复杂度。
应暴露 suspend/Flow 或由调用方/上层管理 CoroutineScope。
本文主张 Repository 不应启动协程,因為這會把並發與執行決策洩漏到資料層,破壞關注點分離。在 Repository 內 launch 協程會隱藏工作執行的位置與控制,增加生命週期管理、取消、錯誤傳播與測試的複雜度,並可能引入執行緒相關錯誤。作者建議由上層或調用端負責啟動協程,或讓 Repository 暴露 suspend 函數、Flow 或接受外部 CoroutineScope/dispatcher,以便上層掌控調度與生命週期。如此可維持清晰邊界、提升可測試性與行為可預期性,為避免架構陷阱的建議做法。
架構陷阱:為什麼你的 Repository 絕不應啟動協程
Repository 不該啟動協程,因為這會把並發控制洩漏到資料層,破壞關注點分離並增加測試與生命週期管理難度。
重點摘要
在 Repository 中啟動協程會違反關注點分離。
會隱藏執行與取消控制,增加測試與生命週期複雜度。
應暴露 suspend/Flow 或由呼叫端/上層管理 CoroutineScope。
本文主張 Repository 不應該啟動協程,因為這會把並發與執行決策洩漏到資料層,破壞關注點分離。於 Repository 內 launch 協程會隱藏工作執行的位置與控制,增加生命週期管理、取消、錯誤傳播與測試的複雜度,並可能引入執行緒相關錯誤。作者建議由上層或呼叫端負責啟動協程,或讓 Repository 暴露 suspend 函式、Flow 或接受外部 CoroutineScope/dispatcher,以便上層掌控調度與生命週期。這樣能維持清晰界線、提升可測試性與行為可預期性,是避免架構陷阱的實作建議。