Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava; How to emit observables synchronously

Tags:

java

rx-java

I want to synchronously emit two Observable objects (which are asynchronous), one after the other where it returns the first emitted Observable object. If the first one fails, it should not emit the second one.

Let's say we have one Observable that signs a user in, and another Observable that automatically selects the user's account, after signing in.

This is what I tried:

public Observable<AccessToken> signInAndSelectAccount(String username, String password)
{

    Observable<AccessToken> ob1 = ...; // Sign in.
    Observable<Account> ob2 = ...; // Select account.


    return Observable.zip(
            ob1,
            ob2,
            new Func2<AccessToken, Account, AccessToken>() {
                @Override
                public AccessToken call(AccessToken accessToken, Account account)
                {
                     return accessToken;
                }
            });
}

This unfortunately does not work for my use case. It will emit/call both observables parallel, starting with 'ob1'.

Did someone encounter a similar use case? Or has an idea on how to make observables wait for eachother in a synchronous way, where the first emitted can be returned?

Thanks in advance.

like image 581
Thomas Neuteboom Avatar asked Jan 28 '16 13:01

Thomas Neuteboom


People also ask

Is RxJava synchronous?

Once the result of your call is available, it is returned via a callback. RxJava is asynchronous, too.

Is RxJava asynchronous?

Even though RxJava is a Reactive Extensions library for the JVM, you can also use it to run asynchronous tasks in the background.

How many times can each of onNext () onComplete () and onError () methods be called?

Exactly once delivery for final events: you are allowed to call either onComplete or onError at most one time. And you cannot call both onComplete and onError . The implementation of onNext , onError or onComplete MUST NOT throw exceptions.

What is onNext in RxJava?

OnNext. conveys an item that is emitted by the Observable to the observer. OnCompleted. indicates that the Observable has completed successfully and that it will be emitting no further items. OnError.


2 Answers

You can also use rx.observables.BlockingObservable e.g.:

BlockingObservable.from(/**/).single();
like image 60
netgui Avatar answered Dec 28 '22 18:12

netgui


You can use Single.blockingGet for synchronous call

// example 
signIn(name,password).blockingGet() 
like image 41
Linh Avatar answered Dec 28 '22 17:12

Linh