协程从不取消或挂起作业后调用API

时间:2020-02-13 21:09:24

标签: kotlin kotlin-coroutines

在其他电话上收到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被称为->获得成功响应

我在其他API调用中得到403

我点击了按钮-> Api不被称为

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

几分钟后我明白了

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

0 个答案:

没有答案