【发布时间】:2019-07-08 15:41:09
【问题描述】:
我在一个用例上,我有一个存储库,其中有我必须做的所有方法,例如:
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)
}
}
【问题讨论】: