如何返回Maybe或Maybe的结果

时间:2019-07-08 15:41:09

标签: android kotlin rx-java

我在用例上,并且有一个存储库,这里有我必须执行的所有方法,例如:

class MyUseCase(
    private val myRepository: MyRepository
) {

    fun execute(example: String) { //First I don't know what to return here
    //Here I have to check if theres anything on the room db, for this I have this method
    myRepository.findLocally(example) // it returns a Maybe<MyObject>
    //Then if it returns an object I have to do another call that is 
    myRepository.findObject(example) //it will return a Maybe<List<OtherObject>>
    //So if we arrive to this, the usecase is done and I should return the last result.
    //if user doesn't search it before then I have to do an api call using
    myRepository.getFromApi(example) //it will return Single<List<OtherObject>>
    //When I get the result then I have to do two inserts using 
    myRepository.insertWord(example) : Completable
    //And then I want to add all the result from the api call it can be a List<MyObject> or a []
    myRepository.insertList(resultFromApi) : Completable

    }

}

我的问题是我现在知道如何执行所有这些操作,或者是否应该拆分它或某些东西,这是从演示者调用的,所以我想将返回给演示者的数据称为view.showData( )。

这个想法应该像这样执行:

if(myRepository.findLocally(example)) {
  return myRepository.findObject(example)
}
else{
  myRepository.getFromApi(example)
  myRepository.insertWord(example)
  myRepository.insertList(resultFromApi)
}


编辑

我正在寻找使用RxJava的方法。

这就是我要尝试的方式:

return myRepository.findLocally(example).flatMap {
            myRepository.findObject(example)
        }.switchIfEmpty {
            myRepository.getFromApi(example).flatMap { example ->
                example.flatMap {
                    myRepository.insertList(
                        MyExample(
                            it.id,
                            it.name,
                            it.description
                        )
                    )
                }
                myRepository.insertWord(example)

            }
        }

1 个答案:

答案 0 :(得分:0)

方法1:
您可以返回Any?对象

private val myRepository() : Any? {
    // Your stuff here
}

Any对象基本上意味着您可以返回所需的任何内容,但要仔细检查父方法中的返回值。
?意味着您还可以返回null对象。在您的父方法中也进行检查。

方法2:
或使用ifelse s从调用此方法的方法进行所有这些调用

方法3:
另一种方法是使用“指针”返回两者:

private val myRepository(resul1 : Object1, result2 : Object2, ...) {
    if (function_to_get_result1_fails)
        result1 = Object1() // You set result1 as a basic empty object of type Object1
    else if (function_to_get_result2_fails)
        result2 = Object2()
    // etc.
}

然后在您的父方法中进行如下检查:

myRepository(object1, object2, ...)
if (object1.someDataInObject1 != -1) // Set an un-instancied variable as -1 to know if the object is empty or not
    doSomething()
else if (object2.someDataInObject2 != -1)
    doSomethingElse()
// etc.

但是,更喜欢方法1或方法2,但是方法3有点“脏”,无所事事地消耗了很多资源。