MVVM架构下Firebase Auth异步代码Repository层实现优化问询
优化Firebase Auth找回密码功能的Repository层实现
问题背景
基于MVVM架构开发应用,使用Firebase Authentication和Cloud Firestore,需将异步操作迁移至Repository层。
原ViewModel中找回密码的实现代码:
fun sendPasswordResetEmail() { auth.sendPasswordResetEmail(emailAddress) .addOnCompleteListener { task -> if (task.isSuccessful) { isSendEmailSuccess.postValue(true) } else { isSendEmailSuccess.postValue(false) } }.addOnFailureListener {e -> if(e is FirebaseAuthException) isSendEmailSuccess.postValue(false) } }
尝试编写的Repository层代码存在冗余(需额外定义result变量):
suspend fun sendPasswordResetEmail(emailAddress: String) : Boolean { var result = false auth.sendPasswordResetEmail(emailAddress) .addOnCompleteListener { task -> if (task.isSuccessful) { result = true } else { result = false } }.addOnFailureListener {e -> result = true }.await() return result }
优化方案
利用Kotlin协程的try-catch结合Firebase Task的await()方法,可实现更简洁清晰的逻辑:
优化后的Repository代码
suspend fun sendPasswordResetEmail(emailAddress: String): Boolean { return try { auth.sendPasswordResetEmail(emailAddress).await() true // 执行至此说明异步操作成功 } catch (e: Exception) { false // 捕获所有异常,统一返回失败 } }
细节说明
- Firebase Task调用
await()后,成功时会直接执行后续代码,失败则抛出对应异常,无需额外添加监听器。 - 若需区分异常类型(如单独处理Firebase认证异常),可细化
catch块:
suspend fun sendPasswordResetEmail(emailAddress: String): Boolean { return try { auth.sendPasswordResetEmail(emailAddress).await() true } catch (e: FirebaseAuthException) { // 针对Firebase认证异常做特殊处理 false } catch (e: Exception) { // 处理其他通用异常 false } }
ViewModel层调用示例
在ViewModel中通过viewModelScope启动协程调用Repository方法:
fun sendPasswordResetEmail() { viewModelScope.launch { val isSuccess = authRepository.sendPasswordResetEmail(emailAddress) isSendEmailSuccess.postValue(isSuccess) } }
内容的提问来源于stack exchange,提问作者Nguyễn Mạnh Cường
相关产品推荐
相关产品推荐

