kotlin - 协程在作业取消或挂起后从不调用 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
解决方案
推荐阅读
- assembly - MIPS bad address/ Exception
- android - Dynamic Listview with EditText not clear values in Same Activity
- osquery - I want to connect my web application to show the reports from osquery SQLITE database
- angular - 下一页中的分页序列号以角度显示?
- java - Anilist api v2 GRAPHQL
- docker - 如何为多个环境创建单个 NGINX.conf 文件
- javascript - 使用反应项目列表中的 getElementById 更改一个项目的点击值是否是好方法
- python - python-docx 不会在 IDE 上自动完成
- java - 在 Android Studio 中需要帮助
- mysql - cause of \xF0\x9F\x98\x94 incorrect string value sql exception?