首页 > 解决方案 > 协程在作业取消或挂起后从不调用 API

问题描述

在其他电话上收到 JobCancellationException 后,单击 loan1 按钮时如何拨打电话?

class MainRepository{

   //called many times
   suspend fun getLoanOptions(): Resource<LoanOptionsResponse> {
        return try {
            val response = apiService.getLoanOptions("id")
            responseHandler.handleSuccess(response)
        } catch (e: Exception) {
            responseHandler.handleException(e)
        }
    }
}
class MainViewModel : ViewModel(), CoroutineScope {

    private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
        Timber.e("$throwable")
    }

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.IO + SupervisorJob() + exceptionHandler

    private val mainRepo: MainRepository by lazy { MainRepository() }

    //extra calls to this fails 
    fun getLoanOptions(): LiveData<Resource<LoanOptionsResponse>> {
        return liveData(coroutineContext) {
            val data = mainRepo.getLoanOptions()
            emit(Resource.loading(null))
            emit(data)

        }
    }

   override fun onCleared() {
        super.onCleared()
        coroutineContext.cancel()
    }

}
 //in mainactivity I call it

 class MainActivity : BaseActivity() {

 val vm: MainViewModel by lazy { ViewModelProvider(this).get(MainViewModel::class.java)  }

   override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)
     setContentView(R.layout.activity_main)

      loan1.setOnClickListener {
         // if any previous api has 403 this one does not work any more ?
         vm.getLoanOptions().observe(this, Observer {
           //data
         }
      }

      loan2.setOnClickListener {

      }

    }
 }


我点击了按钮->调用了Api->得到了成功响应

我再次点击 -> Api is called -> got success response

我在其他 API 调用中得到 403

我点击了按钮 -​​ > Api is not called

在此活动中没有调用其他 Api 调用:(

几分钟后我明白了

kotlinx.coroutines.JobCancellationException: Job was cancelled; job=StandaloneCoroutine

标签: kotlinkotlin-coroutines

解决方案


推荐阅读