拥有下一个数据模型:
data class Response(
private val success: Boolean,
private val error: Error,
private val data: Data
)
我希望success == false
或数据对象错误对象success == true
我Observable
流中的Observable.just(Response(true, Error(), Data()))
.filter { response -> response.success }
.switchIfEmpty { } //Wanted response.error here
.subscribe { response-> } //Wanted response.data here instead of full response.
。
我尝试了以下方法:
<StackLayout Grid.Column="2" Orientation="Vertical" VerticalOptions="Center" WidthRequest="132">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Tapped="shelfOption_Tapped"/>
</StackLayout.GestureRecognizers>
</StackLayout>
有人知道如何实现这个目标吗?
答案 0 :(得分:1)
在这种情况下你应该使用密封类
sealed class Response {
data class Success(val data: Data) : Response()
data class Error(val error: Error) : Response()
}
并进入你的rx observable:
... //observableChain
.subscribe { result: Response ->
when (result) {
is Success -> handleSuccess(result.data)
is Error -> handleError(result.error)
}
}
答案 1 :(得分:0)
我使用flatMap
代替filter
实现了我的目标,这使我能够实现if-else
流程:
Observable.just(Response(true, Error(), Data()))
.flatMap { response ->
if(response.success) Observable.just(response.error)
else Observable.just(response.data)
}
.subscribe { result->
when(result) {
is Data -> //handle data
is Error -> //handle error
}
}