简体   繁体   English

如果最后一次操作以异常结束,Kotlin协程会立即给出异常

[英]Kotlin coroutine immediately give an exception if last operation finished with exception

When I was try to login on my service via retrofit. 当我尝试通过改造登录我的服务时。 When my service is off, 10 seconds after clicking the button I got an SocketTimeoutException exception. 当我的服务关闭时,单击按钮10秒后,我收到了SocketTimeoutException异常。 So far everything is normal but again, I clicked the button again after the error gave the same error immediately. 到目前为止一切正常但是再次,在错误立即给出相同的错误之后我再次单击该按钮。 What's wrong? 怎么了?

interface LoginService {

    @FormUrlEncoded
    @POST("/login")
    fun login(@Field("id") id: String, @Field("pw") pw: String): Deferred<Response<User>>

}

class LoginViewModel : ViewModel() {

    private var job: Job = Job()
    private val scope: CoroutineScope = CoroutineScope(Dispatchers.Main + job)
    private val service by lazy { RetrofitApiFactory().create(LoginService::class.java) }
    private val excHandler = CoroutineExceptionHandler { _, throwable ->
        Timber.e(throwable);
    }

    fun doLogin(id: String, pw: String) {
        scope.launch(excHandler) {
            val response = service.login(id, pw).await()
            if (response.isSuccessful) {
                response.body()
                        ?.let { user -> doOnSuccess(user) }
                        ?: doOnError(InvalidUserException())
            } else doOnError(Exception())
        }
    }

    private fun CoroutineScope.doOnError(e: Throwable) {
        excHandler.handleException(coroutineContext, e)
    }

    private fun doOnSuccess(user: User) {
        ...
    }

    override fun onCleared() {
        job.cancel()
    }

}

You need to change your CoroutineScope to not re-use the same Job . 您需要更改CoroutineScope以不重复使用相同的Job It's already considered as failed , so it will not even begin executing. 它已被视为失败 ,因此它甚至不会开始执行。

See related issue on github . 请参阅github上的相关问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM