0

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

}

1 Answer 1

0

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) {
           
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.