gpt4 book ai didi

android - 如何从协程返回错误响应

转载 作者:行者123 更新时间:2023-11-29 18:30:57 25 4
gpt4 key购买 nike

我正在尝试将我所有的回调更改为协程,我已经阅读了它们并且它们很吸引人!

我想要完成的只是登录一个用户,但如果登录逻辑失败,请通知我的演示者。

这是我做的

登录Presenter.kt

class LoginPresenter @Inject constructor(private val signInInteractor: SignInInteractor) : LoginContract.Presenter, CoroutineScope {

private val job = Job()
override val coroutineContext: CoroutineContext = job + Dispatchers.Main

override fun signInWithCoroutines(email: String, password: String) {

launch {
view?.showProgress()
withContext(Dispatchers.IO){
signInInteractor.signInWithCoroutinesTest(email,password)
}
view?.hideProgress()
}

}
}

现在问题出在我的交互器上,因为它是一个挂起函数,我很乐意返回一个错误响应,以便从我的演示者那里执行 view.showError(errorMsg)

登录交互器.kt

 override suspend fun signInWithCoroutinesTest(email: String, password: String) {
FirebaseAuth.getInstance()?.signInWithEmailAndPassword(email, password).addOnCompleteListener {
if(it.isSuccessful){
//Want to notify the presenter that the coroutine has ended succefully
}else{
//want to let the courutine know about it.exception.message.tostring
}
}

}

我这样做的方式是通过回调通知我的演示者

 override fun signInWithCoroutinesTest(email: String, password: String) {
FirebaseAuth.getInstance()?.signInWithEmailAndPassword(email, password,listener:OnSuccessCallback).addOnCompleteListener {
if(it.isSuccessful){
listener.onSuccess()
}else{
listener.onFailure(it.exception.message.toString())
}
}


}

问题

如果协程操作成功,如何返回并通知我的演示者?

谢谢

最佳答案

您必须明确暂停协程:

override suspend fun signInWithCoroutinesTest(
email: String, password: String
) = suspendCancellableCoroutine { continuation ->
FirebaseAuth.getInstance()?.signInWithEmailAndPassword(email, password).addOnCompleteListener {
if (it.isSuccessful) {
continuation.resume(Unit)
} else {
continuation.resumeWithException(it.exception)
}
}
}

此外,由于您的代码是可挂起的且不会阻塞,因此不要运行它 withContext(IO)。只需直接从主线程调用它,这就是协程的美妙之处。

关于android - 如何从协程返回错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56293838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com