首页 > 解决方案 > 使用任何一个与 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
}

谢谢

标签: androidfirebasekotlingoogle-cloud-firestoreeither

解决方案


您可以使用接口使其返回您想要的内容,或者我更愿意发送高阶函数并在您想要的地方使用它。

你的代码将是这样的

  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)
        }
}

你可能会发现复杂的错误,但这是为了证明我的想法


推荐阅读