android - 使用任何一个与 Firestore
问题描述
我正在尝试将 Either 与 Firestore 一起使用,我拥有的功能就是这个
fun setDataIntoFirestore(data: HashMap<String,Any>): Either<Failure,Boolean>{
db.collection("test")
.add(data)
.addOnSuccessListener {
//Here I need Either.Right(true);
}
.addOnFailureListener {
Log.d("FirestoreData", "Failure: " + it.message)
//Here I want to add Either.Left(it)
}
}
我正在尝试这样做,因为我想在将数据添加到数据库时通知我的视图,但是当我将函数标记为返回时,我需要返回该类型并且我无法在任务中返回任何建议我。
关于如何实现这一点的任何想法?
我像这样从我的用例中调用这个方法
class SendProductUseCase: UseCase<Boolean, HashMap<String, Any>>() {
private val repo = SendProductRepo()
override suspend fun run(params: HashMap<String, Any>): Either<Failure, Boolean> {
return repo.setDataIntoFirestore(params)
}
}
并且 UseCase 是每个的通用 UseCase
abstract class UseCase<out Type, in Params> where Type : Any {
abstract suspend fun run(params: Params): Either<Failure, Type>
operator fun invoke(params: Params, onResult: (Either<Failure, Type>) -> Unit = {}) {
val job = GlobalScope.async(Dispatchers.Default) { run(params) }
GlobalScope.launch(Dispatchers.Main) { onResult(job.await()) }
}
class None
}
谢谢
解决方案
您可以使用接口使其返回您想要的内容,或者我更愿意发送高阶函数并在您想要的地方使用它。
你的代码将是这样的
fun setDataIntoFirestore(data: HashMap<String,Any> , retValue : (Either<Failure,Boolean>) -> (Unit)){
db.collection("test")
.add(data)
.addOnSuccessListener {
retValue.invoke(Either.Right(true))
}
.addOnFailureListener {
Log.d("FirestoreData", "Failure: " + it.message)
//Here I want to add Either.Left(it)
}
}
你可能会发现复杂的错误,但这是为了证明我的想法
推荐阅读
- java - 检查位是否已设置或未给出其在 java 中的位置(一个 Hackerrank 问题)
- excel-formula - 拖动到其他列时如何在 Excel 中使用列名保持列引用不变
- python - 我如何从字典中获取最大的键?
- javascript - Jquery:选中“全选”时选中所有复选框
- java - 从java中的字符串中提取两个可变长度浮点值。“lat=22.3456&lon=54.1234”,位数并不总是固定的
- php - 类别和子类别的集合?
- php - WP_Query 用于帖子关系和自定义帖子类型
- php - 使用 PDO (PHP) 在 mySQL 数据库中插入数字数据
- angular - Cordova 中的 Razorpay 集成 [RazorPayCheckout 未定义]
- python - GET 404 未能在烧瓶引导程序中加载资源错误