RxJava; How to emit observables synchronously

后端 未结 4 1053
不知归路
不知归路 2021-01-11 14:33

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

相关标签:
4条回答
  • 2021-01-11 14:55

    I don't know Java, but the solution in Scala would probably be this, hope it is readable to you

    import rx.lang.scala.Observable
    
    class AccessToken
    class Account
    
    case class TokenAndAccount(token: AccessToken, account: Account)
    
    val accessTokenSource = Observable.just(new AccessToken)
    val accountSource = Observable.just(new Account)
    
    accessTokenSource
       .flatMap(token ⇒ accountSource.map(account ⇒ TokenAndAccount(token, account)))
       .subscribe(tokenAndAccount ⇒ println(tokenAndAccount))
    

    Basically flatMap will make sure that the accountSource.map... is used only after the token from accessTokenSource has been emitted. Inside the accountSource.map we combine the obtained token and account together for later usage in subscribe.

    flatMap is one of the most useful operators, be sure to read it's docs and perhaps some tutorials.

    0 讨论(0)
  • 2021-01-11 14:59

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

    BlockingObservable.from(/**/).single();
    
    0 讨论(0)
  • 2021-01-11 14:59

    You can use Single.blockingGet for synchronous call

    // example 
    signIn(name,password).blockingGet() 
    
    0 讨论(0)
  • 2021-01-11 15:07

    There is no such term as "wait" in reactive programming. You need to think about creating of a data stream, where one Observable could be triggered by another. In your case after receiving token you need to receive account. It could look like this:

    Observable<Account> accountObservable = Observable.create(new Observable.OnSubscribe<AccessToken>() {
        @Override public void call(Subscriber<? super AccessToken> subscriber) {
            subscriber.onNext(new AccessToken());
            subscriber.onCompleted();
        }
    }).flatMap(accessToken -> Observable.create(new Observable.OnSubscribe<Account>() {
        @Override public void call(Subscriber<? super Account> subscriber) {
            subscriber.onNext(new Account(accessToken));
            subscriber.onCompleted();
        }
    }));
    
    0 讨论(0)
提交回复
热议问题