waqar saeed
waqar saeed

Reputation: 64

How to cancel api request in view model in Mvvm?

I am try to cancel to api request if user calls api to fast then only the latest api should return the result all previous requests should be discarded but this isn't working anyone knows the solution please help thanks

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

private var requestCalculation: Job? = null

fun recalculate() {

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

}

Upvotes: 0

Views: 820

Answers (1)

waqar saeed
waqar saeed

Reputation: 64

Adding a check after api call this.isActive {return@launch} finally worked for me...

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

Upvotes: 0

Related Questions