簡體   English   中英

如何在 GlobalScope 一之后排隊 Coroutines viewModelScope 作業

[英]How to enqueue Coroutines viewModelScope job after GlobalScope one

我有一個應用程序作用域函數,它像這樣從服務器請求訪問令牌

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
}

但是當不同存儲庫中有許多不同的數據請求時,這是正確的使用方法嗎?

您可以執行以下操作:

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){}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM