【问题标题】:How to cancel api request in view model in Mvvm?如何在 Mvvm 的视图模型中取消 api 请求?
【发布时间】:2021-05-18 10:41:56
【问题描述】:

如果用户快速调用 api,我会尝试取消对 api 请求,那么只有最新的 api 应该返回结果,所有以前的请求都应该被丢弃,但这不起作用任何知道解决方案的人请帮助谢谢

class CartViewModel(val store: Account) : BaseViewModel() {

private var requestCalculation:工作? = 空

有趣的重新计算(){

    requestCalculation.let {
        if (it != null) {
            if (it.isActive) {
                requestCalculation!!.cancel()
            }
        }
    }

    requestCalculation = viewModelScope.launch(Dispatchers.IO) {
        isLoading.postValue(true)
        try {
            val order = CCOrderManager.shared.calculateTaxesAndApplyRewards(store.id)
            refreshOrder()

        } catch (e: Exception) {
            exception.postValue(e.localizedMessage ?: e.toString())
        }
    }
}

}

【问题讨论】:

    标签: android api kotlin mvvm viewmodel


    【解决方案1】:

    取消和执行的顺序错误。函数启动时requestCalculation为空,无法取消。确保首先启动协程,然后再取消它。例如:

    private var requestCalculation: Job? = null
    
    fun recalculate() {
    
        requestCalculation = viewModelScope.launch(Dispatchers.IO) {
            delay(10_000)
            // do your work...
        }
        
        // now the job can be canceled
        requestCalculation?.cancel()
    }
    

    【讨论】:

      【解决方案2】:

      在 api 调用 this.isActive {return@launch} 后添加检查终于为我工作了......

      fun recalculate() {
          calculationRequest?.cancel()
          isLoading.postValue(true)
          calculationRequest = viewModelScope.launch(Dispatchers.IO) {
              try {
                  val order = 
                 CCOrderManager.shared.calculateTaxesAndApplyRewards(store.id)
             // this check is the solution   *******             
             if (!this.isActive) {return@launch}
                  val catalog = CatalogManager.shared().catalog
                  
              } catch (e: Exception) {
                 
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-24
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-14
        • 1970-01-01
        相关资源
        最近更新 更多