Android 中的协程最佳实践

本页面介绍了多项最佳实践,在 Android 中使用协程时,采用这些实践可以提升应用的扩展性和可测试性。

注入 Dispatcher

在创建新协程或调用 withContext 时,不要硬编码 Dispatchers

// DO inject Dispatchers
class NewsRepository(
    private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
) {
    suspend fun loadNews() = withContext(defaultDispatcher) { /* ... */ }
}

// DO NOT hardcode Dispatchers
class NewsRepository {
    // DO NOT use Dispatchers.Default directly, inject it instead
    suspend fun loadNews() = withContext(Dispatchers.Default) { /* ... */ }
}

这种依赖注入模式让测试变得更容易,因为您可以在单元测试和插桩测试中用测试调度程序 (test dispatcher) 替换这些调度程序,从而使测试更具确定性。

挂起函数应支持从主线程安全调用

挂起函数应当是“主线程安全”的,这意味着它们可以安全地从主线程调用。如果一个类在协程中执行长时间运行的阻塞操作,则该类有责任使用 withContext 将执行移出主线程。这适用于应用中的所有类,无论该类处于架构的哪个部分。

class NewsRepository(private val ioDispatcher: CoroutineDispatcher) {

    // As this operation is manually retrieving the news from the server
    // using a blocking HttpURLConnection, it needs to move the execution
    // to an IO dispatcher to make it main-safe
    suspend fun fetchLatestNews(): List<Article> {
        withContext(ioDispatcher) { /* ... implementation ... */ }
    }
}

// This use case fetches the latest news and the associated author.
class GetLatestNewsWithAuthorsUseCase(
    private val newsRepository: NewsRepository,
    private val authorsRepository: AuthorsRepository
) {
    // This method doesn't need to worry about moving the execution of the
    // coroutine to a different thread as newsRepository is main-safe.
    // The work done in the coroutine is lightweight as it only creates
    // a list and add elements to it
    suspend operator fun invoke(): List<ArticleWithAuthor> {
        val news = newsRepository.fetchLatestNews()

        val response: List<ArticleWithAuthor> = mutableEmptyList()
        for (article in news) {
            val author = authorsRepository.getAuthor(article.author)
            response.add(ArticleWithAuthor(article, author))
        }
        return Result.Success(response)
    }
}

这种模式使应用更具扩展性,因为调用挂起函数的类无需关心应该为哪种类型的工作使用哪个 Dispatcher。这种责任由执行工作的类承担。

应由 ViewModel 创建协程

ViewModel 类应优先创建协程,而不是公开挂起函数来执行业务逻辑。如果不是通过数据流公开状态,而只需要发出单个值,那么 ViewModel 中的挂起函数可能很有用。

// DO create coroutines in the ViewModel
class LatestNewsViewModel(
    private val getLatestNewsWithAuthors: GetLatestNewsWithAuthorsUseCase
) : ViewModel() {

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

    fun loadNews() {
        viewModelScope.launch {
            val latestNewsWithAuthors = getLatestNewsWithAuthors()
            _uiState.value = LatestNewsUiState.Success(latestNewsWithAuthors)
        }
    }
}

// Prefer observable state rather than suspend functions from the ViewModel
class LatestNewsViewModel(
    private val getLatestNewsWithAuthors: GetLatestNewsWithAuthorsUseCase
) : ViewModel() {
    // DO NOT do this. News would probably need to be refreshed as well.
    // Instead of exposing a single value with a suspend function, news should
    // be exposed using a stream of data as in the code snippet above.
    suspend fun loadNews() = getLatestNewsWithAuthors()
}

视图 (Views) 不应直接触发任何协程来执行业务逻辑。相反,应将该责任委派给 ViewModel。这使得业务逻辑更容易测试,因为您可以对 ViewModel 对象进行单元测试,而无需使用测试视图所需的插桩测试。

此外,如果工作是在 viewModelScope 中启动的,您的协程将自动在配置更改(如屏幕旋转)中存活。如果您改用 lifecycleScope 创建协程,则必须手动处理这些情况。如果协程的生命周期需要超出 ViewModel 的作用域,请参阅在业务层和数据层创建协程一节。

不要公开可变类型

倾向于向其他类公开不可变类型。通过这种方式,对可变类型的所有更改都集中在一个类中,从而在出现问题时更容易进行调试。

// DO expose immutable types
class LatestNewsViewModel : ViewModel() {

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

    /* ... */
}

class LatestNewsViewModel : ViewModel() {

    // DO NOT expose mutable types
    val uiState = MutableStateFlow(LatestNewsUiState.Loading)

    /* ... */
}

数据层和业务层应公开挂起函数和 Flow

数据层和业务层中的类通常公开函数来执行一次性调用,或在一段时间内通知数据更改。这些层中的类应该公开用于一次性调用的挂起函数用于通知数据更改的 Flow

// Classes in the data and business layer expose
// either suspend functions or Flows
class ExampleRepository {
    suspend fun makeNetworkRequest() { /* ... */ }

    fun getExamples(): Flow<Example> { /* ... */ }
}

这一最佳实践使调用者(通常是表示层)能够控制这些层中正在进行的工作的执行和生命周期,并在需要时取消工作。

在业务层和数据层创建协程

对于数据层或业务层中因各种原因需要创建协程的类,有不同的选项。

如果这些协程中要执行的工作仅在用户处于当前屏幕时才有意义,则应遵循调用者的生命周期。在大多数情况下,调用者将是 ViewModel,当用户离开屏幕且 ViewModel 被清除时,调用将被取消。在这种情况下,应使用 coroutineScopesupervisorScope

class GetAllBooksAndAuthorsUseCase(
    private val booksRepository: BooksRepository,
    private val authorsRepository: AuthorsRepository,
) {
    suspend fun getBookAndAuthors(): BookAndAuthors {
        // In parallel, fetch books and authors and return when both requests
        // complete and the data is ready
        return coroutineScope {
            val books = async { booksRepository.getAllBooks() }
            val authors = async { authorsRepository.getAllAuthors() }
            BookAndAuthors(books.await(), authors.await())
        }
    }
}

如果工作只要应用开启就一直有意义,且该工作不绑定到特定屏幕,则该工作应超出调用者的生命周期。对于这种情况,应使用外部 CoroutineScope,详见协程与不应取消的工作模式博客文章

class ArticlesRepository(
    private val articlesDataSource: ArticlesDataSource,
    private val externalScope: CoroutineScope,
) {
    // As we want to complete bookmarking the article even if the user moves
    // away from the screen, the work is done creating a new coroutine
    // from an external scope
    suspend fun bookmarkArticle(article: Article) {
        externalScope.launch { articlesDataSource.bookmarkArticle(article) }
            .join() // Wait for the coroutine to complete
    }
}

externalScope 应由生命周期比当前屏幕更长的类创建和管理,例如由 Application 类或作用域限定为导航图 (navigation graph) 的 ViewModel 管理。

在测试中注入 TestDispatchers

在测试中,应将 TestDispatcher 的实例注入到您的类中。kotlinx-coroutines-test中有两种可用的实现:

  • StandardTestDispatcher:将启动的协程放入调度程序队列中,并在测试线程空闲时执行它们。您可以使用 advanceUntilIdle 等方法挂起测试线程,以允许其他排队的协程运行。

  • UnconfinedTestDispatcher:以阻塞方式迫切地运行新协程。这通常使编写测试更容易,但在测试期间对协程的执行方式控制较少。

有关详细信息,请参阅每种调度程序实现的文档。

要测试协程,请使用 runTest 协程构建器。runTest 使用 TestCoroutineScheduler 来跳过测试中的延迟,并允许您控制虚拟时间。您还可以根据需要使用此调度程序来创建其他测试调度程序。

class ArticlesRepositoryTest {

    @Test
    fun testBookmarkArticle() = runTest {
        // Pass the testScheduler provided by runTest's coroutine scope to
        // the test dispatcher
        val testDispatcher = UnconfinedTestDispatcher(testScheduler)

        val articlesDataSource = FakeArticlesDataSource()
        val repository = ArticlesRepository(
            articlesDataSource,
            testDispatcher
        )
        val article = Article()
        repository.bookmarkArticle(article)
        assertThat(articlesDataSource.isBookmarked(article)).isTrue()
    }
}

所有 TestDispatchers 都应共享同一个调度程序。这允许您在单个测试线程上运行所有协程代码,从而使测试具有确定性。runTest 会等待同一调度程序上的所有协程或测试协程的所有子协程完成后才会返回。

避免使用 GlobalScope

这与“注入 Dispatcher”的最佳实践类似。通过使用 GlobalScope,您实际上是在硬编码类所使用的 CoroutineScope,这会带来一些弊端:

  • 助长了硬编码值。如果您硬编码了 GlobalScope,可能也会顺便硬编码 Dispatchers

  • 使测试变得非常困难,因为您的代码是在不受控制的作用域中执行的,您将无法控制其执行。

  • 无法为作用域本身构建的所有协程拥有一个通用的 CoroutineContext

相反,考虑为需要超出当前作用域的工作注入一个 CoroutineScope。查看在业务层和数据层创建协程一节,了解更多关于此主题的内容。

// DO inject an external scope instead of using GlobalScope.
// GlobalScope can be used indirectly. Here as a default parameter makes sense.
class ArticlesRepository(
    private val articlesDataSource: ArticlesDataSource,
    private val externalScope: CoroutineScope = GlobalScope,
    private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default
) {
    // As we want to complete bookmarking the article even if the user moves
    // away from the screen, the work is done creating a new coroutine
    // from an external scope
    suspend fun bookmarkArticle(article: Article) {
        externalScope.launch(defaultDispatcher) {
            articlesDataSource.bookmarkArticle(article)
        }
            .join() // Wait for the coroutine to complete
    }
}

// DO NOT use GlobalScope directly
class ArticlesRepository(
    private val articlesDataSource: ArticlesDataSource,
) {
    // As we want to complete bookmarking the article even if the user moves away
    // from the screen, the work is done creating a new coroutine with GlobalScope
    suspend fun bookmarkArticle(article: Article) {
        GlobalScope.launch {
            articlesDataSource.bookmarkArticle(article)
        }
            .join() // Wait for the coroutine to complete
    }
}

协程与不应取消的工作模式博客文章中了解关于 GlobalScope 及其替代方案的更多信息。

确保您的协程是可取消的

协程中的取消是协作式的,这意味着当协程的 Job 被取消时,协程不会立即停止,直到它挂起或检查取消状态为止。如果您在协程中执行阻塞操作,请确保协程是可取消的

例如,如果您正在从磁盘读取多个文件,在开始读取每个文件之前,请检查协程是否已被取消。检查取消的一种方法是调用 ensureActive 函数。

someScope.launch {
    for(file in files) {
        ensureActive() // Check for cancellation
        readFile(file)
    }
}

kotlinx.coroutines 中的所有挂起函数(如 withContextdelay)都是可取消的。如果您的协程调用了它们,则无需执行任何额外工作。

有关协程取消的更多信息,请查看协程中的取消博客文章

留意异常

协程中未捕获的异常会导致应用崩溃。如果可能发生异常,请在由 viewModelScopelifecycleScope 创建的协程体中捕获它们。

class LoginViewModel(
    private val loginRepository: LoginRepository
) : ViewModel() {

    fun login(username: String, token: String) {
        viewModelScope.launch {
            try {
                loginRepository.login(username, token)
                // Notify view user logged in successfully
            } catch (exception: IOException) {
                // Notify view login attempt failed
            }
        }
    }
}

有关更多信息,请查看博客文章协程中的异常,或 Kotlin 文档中的协程异常处理

了解更多关于协程的信息

如需更多协程资源,请参阅Kotlin 协程和 Flow 的其他资源页面。