1

目前,我正在尝试通过改进不同调度程序和上下文的使用来优化我的应用程序性能。我偶然发现的一个问题是,如果我在带有 IO Dispatcher 的协程内启动一个挂起函数,那么其他所有函数是否也会在同一个调度程序中执行?

例子

fun doSomething() {
    viewModelScope.launch(Dispatchers.IO) {
       getUserData(viewModelScope)
    }
}

fun getUserData(innerScope: CoroutineScope) {
    workerList.startUserDataWorker()
    observeUserData(innerScope) // suspend function, is this called inside the IO Dipatcher?
}

// Will this be called inside the IO Dispatcher?
private suspend fun observeUserData(innerScope: CoroutineScope) {
    observerWorkerStateAndPassData(workerList.userDataWorkInfo, USER_DATA_OUTPUT_OPTION).collect { status ->
        when(status) {
            is Status.Loading -> {
                _userDataState.postValue(Status.loading())
            }
            is Status.Success -> {
                 // Will getShippingAddressList() also be called on the IO Dispatcher?
                _userDataState.postValue(Status.success(getShippingAddressList()))
            }
            is Status.Failure -> {
                _userDataState.postValue(Status.failed(status.message.toString()))
            }
        }
    }
}

// Getting Address from the local room cache. Is this called on the IO Dispatcher?
private suspend fun getShippingAddressList(): List<UserDeliveryAddress> {
    val uncachedList = userAddressDao.getAllAddress(UserAddressCacheOrder.SHIPPING)
    return userAddressCacheMapper.mapFromEntityList(uncachedList)
}
4

1 回答 1

2

调用挂起函数时,您使用的调度程序无关紧要。仅在调用阻塞函数时才相关。挂起不使用调度程序线程。

例外:

  • 您的挂起功能设计不当,实际上是阻塞的。
  • 如果您正在跨多个同时协同程序处理对象,则并发影响。例如,如果您只使用 Main 或单线程调度程序接触特定对象,则不必担心多个线程同时接触它。我会主张适当的封装,您应该始终使用关注对象的这些用法进行包装,withContext(mySingleThreadDispatcher)因此哪个调度程序调用您的挂起函数仍然无关紧要。

在您的示例中,调度程序调用什么并不重要,observeUserData因为该函数将在收集时无限期挂起。并且当它收集时,它只调用非阻塞、线程安全的函数LiveData.postValue()

于 2021-07-12T13:48:49.023 回答