Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava: How to extract object from observable?

Tags:

java

rx-java

I feel like this is a dumb question, but I couldn't find any answer for a while, so I'm gonna ask it, sorry :)

So, I need a function that does the following:

1) Calls another function to create an Observable User

2) Gets the User object from the Observable User

3) Gets some info about the user and runs through some logic

4) Returns Observable User

I am having troubles with step #2. How do I do that? Or, is this approach somehow fundamentally wrong?

Here's the "model" of the function:

@Override protected Observable buildUseCaseObservable(){

    Observable<User> userObservable = userRepository.findUserByUsername(username);

    //User user = ??????

    //if (...) {...}

    return userObservable;
}

Thank you :)

like image 803
Daniil Orekhov Avatar asked Aug 03 '16 13:08

Daniil Orekhov


1 Answers

You can use operators(map, flatMap, doOnNext, etc) to get the object wrapped by your observable through the pipeline

     Observable.just("hello world")
               .map(sentence-> sentence.toUpperCase) --> do whatever you need.
               .subscribe(sentence -> println(sentence)

By design Observable follow the Observer patter, which subscribe to the observable and receive the item once has been emitted through the pipeline.

Also what you can do is instead use observer patter, just extract the object from the pipeline using toBlocking. But that´s is consider an anti pattern and means you´re not applying a good design.

          @Test
public void observableEvolveAndReturnToStringValue() {
    assertTrue(Observable.just(10)
                         .map(String::valueOf)
                         .toBlocking()
                         .single()
                         .equals("10"));
}

You can see more examples about to Blocking here https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/utils/ObservableToBlocking.java

like image 58
paul Avatar answered Nov 03 '22 20:11

paul