目前,我正在尝试通过改进不同调度程序和上下文的使用来优化我的应用程序性能。我偶然发现的一个问题是,如果我在带有 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)
}