RxJava introduced Single<T>. How do I convert an Observable<T> to a Single<T>?

岁酱吖の 提交于 2020-04-29 07:18:07

问题


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?

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?

A pinch more background

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)


回答1:


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

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: Emits the first element or a NoSuchElementException if the source is empty.

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

elementAtOrError: Emits the indexth element or a NoSuchElementException.

More info on this page: https://github.com/ReactiveX/RxJava/wiki/What%27s-different-in-2.0




回答2:


Note: This is for RxJava 1. See other answers below/above for Rx2 :)


2 new convenience methods were added to accomplish this very thing.

toSingle() converts an Observable that emits a single item into a Single that emits that item

toObservable converts a Single into an Observable that emits the item emitted by the Single and then completes

(source: http://reactivex.io/documentation/single.html)




回答3:


In rxjava2 you can use Single.fromObservable().



来源:https://stackoverflow.com/questions/36627927/rxjava-introduced-singlet-how-do-i-convert-an-observablet-to-a-singlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!