RxJava引入了Single T.如何转换Observable< T>到单个T? [英] RxJava introduced Single<T>. How do I convert an Observable<T> to a Single<T>?

查看:781
本文介绍了RxJava引入了Single T.如何转换Observable< T>到单个T?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

RxJava最近引入了.有没有一种方法可以将已经存在的Observable(几乎是Single)转换为Single,而无需修改原始Observable的来源?

RxJava recently introduced Single. Is there a way to convert an already existing Observable (that's pretty much a Single) to a Single without modifying the source of the original observable?

例如,我有一个api服务类,该类的方法返回一个Observable-本质上是从远程资源中获取User.说我无法修改服务.我想在其他地方使用它,但返回一个Single.我该怎么做?

For example, I have an api service class with a method that returns an Observable - which is essentially fetching a User from a remote resource. Say I can't modify the service. I want to consume this elsewhere but return a Single. How do I do this?

更多背景

RxJava最近引入了Single的概念,它或多或少是Rx友好的简单回调(即,可观察的发出一个对象或错误)(在此处了解更多信息-

RxJava recently introduced the concept of a Single which is more or less an Rx friendly simple callback (i.e. an Observable emitting one object or an error) (read more about it here - http://reactivex.io/documentation/single.html)

推荐答案

我认为另一个答案已过时.您可能应该检查以下方法.

I think another answer is outdated. You should probably check the following methods.

singleOrError::如果源大于1个项目,则发出唯一的元素IndexOutOfBoundsException;如果源为空,则发出NoSuchElementException.

singleOrError: Emits the one and only element, IndexOutOfBoundsException if the source is longer than 1 item or a NoSuchElementException if the source is empty.

firstOrError::如果源为空,则发出第一​​个元素或NoSuchElementException.

firstOrError: Emits the first element or a NoSuchElementException if the source is empty.

lastOrError::如果源为空,则发出lastelement或NoSuchElementException.

lastOrError: Emits the lastelement or a NoSuchElementException if the source is empty.

elementAtOrError:发出索引元素或NoSuchElementException.

elementAtOrError: Emits the indexth element or a NoSuchElementException.

此页上的更多信息: https://github. com/ReactiveX/RxJava/wiki/What%27s-different-in-2.0

这篇关于RxJava引入了Single T.如何转换Observable< T>到单个T?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆