3

I want to get emitted items from an Observable stream.

I can do this in Collection streams with the following code:

List<String> items = Arrays.asList("a", "b");
String result = items.stream().filter(i -> i.equals("a")).findFirst().orElse("");

I want to do the same thing with RxJava Observable. I tried this but it returns an Observable<String> not a String.

Observable<String> result2 = Observable.from(items).filter(i -> i.equals("a")).firstOrDefault("");
Mert Nuhoglu
  • 9,695
  • 16
  • 79
  • 117

1 Answers1

4

There is a way to get a BlockingObservable<T> which is synchronous and against the push model of reactive programming. See the comment in the javadoc (Link to Blocking Operations):

BlockingObservable is a variety of Observable that provides blocking operators. It can be useful for testing and demo purposes, but is generally inappropriate for production applications (if you think you need to use a BlockingObservable this is usually a sign that you should rethink your design).

So the solution to your problem looks like:

List<String> items = Arrays.asList("a", "b");
String result = Observable.from(items).filter(i -> i.equals("a"))
                          .toBlocking().firstOrDefault("");
System.out.println(result);
Flown
  • 11,480
  • 3
  • 45
  • 62