【问题标题】:How to enqueue Coroutines viewModelScope job after GlobalScope one如何在 GlobalScope 一之后将 Coroutines viewModelScope 作业排入队列
【发布时间】:2020-01-28 17:28:26
【问题描述】:

我有一个应用程序范围函数,它像这样从服务器请求访问令牌

fun getToken() {
    GlobalScope.launch {
        ...
        val response = webservice.getToken().awaitResponse()
        //save token
    }
}

我在存储库中也有一些函数,这些函数从服务器请求数据并从视图模型中启动,就像这样

//in a ViewModel
fun getData() {
    viewModelScope.launch(Dispatchers.IO) {
        repository.getData()
    }
}

//in a Repository
fun getData() {
    ...
    val response = webservice.getData().awaitResponse()
    //handle response
}

如何使数据请求仅在有可用访问令牌时才发送?

我唯一想到的就是在每次这​​样的数据请求之前检查并请求令牌(如果需要)

fun getData() {
    var response: Response
    token?.let {
        response = webservice.getToken().awaitResponse()
        //save token
    }
    ...
    response = webservice.getData().awaitResponse()
    //handle response
}

但是,当不同的存储库中有许多不同的数据请求时,使用这种方法是否正确?

【问题讨论】:

    标签: android kotlin kotlin-coroutines


    【解决方案1】:

    你可以这样做:

    object InternalScope {
        private val tokenJob = GlobalScope.launch {
            response = webservice.getToken().awaitResponse()
        }
    
        suspend fun <T> runWithContext(
            context: CoroutineContext,
            block: suspend CoroutineScope.() -> T
        ): T {
            tokenJob.join()
            return withContext(context, block)
        }
    }
    

    你可以像这样使用它:

    InternalScope.runWithContext(Dispatchers.IO){}
    

    【讨论】:

    • 我对协程很陌生。你能详细说明一下如何使用它吗?
    • @yaugenka 你知道如何在协程中使用withContext(){}吗?
    • 我像这样使用它:launch { val result = withContext(Dispatchers.IO) {} }
    • 好的,现在将withContext 替换为InternalScope.runWithContext。就是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2022-08-20
    • 1970-01-01
    相关资源
    最近更新 更多