【发布时间】:2019-12-17 15:51:56
【问题描述】:
在我的存储库类中,我正在调用 webservice。如果查询不为空,则返回可流动的结果,如果查询为空,则返回空。然后在我的 ViewModel 中,我将 flowable 转换为 LiveData。
下面是sn-p的代码:
在 myRepository 类中:
fun fetchToDosFromServer(fullQueryString: String?)
: Flowable<GitResult>?
{
if(fullQueryString.length>0)
{ //call webservice- which return observable<GitResult>
var returnedResult = myWebServiceCall()
return returnedData.toFlowable(BackpressureStrategy.BUFFER)
}
else
return null
}
在 myViewModel 类中:
fun getReposFromServer()
{
val resultFromApiCall_flowable : Flowable<GitResult>? = mainRepository.fetchToDosFromServer("q=2")
val source: LiveData<GitResult> = LiveDataReactiveStreams.fromPublisher(resultFromApiCall_flowable)
}
但在 myViewModel 类中尝试将 flowable 转换为 LiveData 时显示编译时错误。行内:
LiveDataReactiveStreams.fromPublisher(resultFromApiCall_flowable)
错误是:
错误:需要 Flowable ,找到 Flowable?
我该如何解决?
【问题讨论】:
-
@coroutineDispatcher:不起作用
-
val resultFromApiCall_flowable : Flowable<GitResult>? = mainRepository.fetchToDosFromServer("q=2")是可选的。因此,您可以使用val resultFromApiCall_flowable : Flowable<GitResult>! = ..强制强制转换,或者您进行空检查。resultFromApiCall_flowable?.let { val source: LiveData<GitResult> = LiveDataReactiveStreams.fromPublisher(it) } -
@kuzdu :我使用了第二个选项并且它有效。谢谢。但是我还有另一个困惑..如果我使用
if(resultFromApiCall_flowable!=null) { val source: LiveData<GitResult> = LiveDataReactiveStreams.fromPublisher(resultFromApiCall_flowable) },那么错误也会消失。但是和xx?.let{...}一样吗 -
是的,但是你可以在这里更方便地处理
else。
标签: kotlin