简体   繁体   English

如何将异步调用转换为同步?

[英]How to convert async call into sync?

I'm pretty new to RxJava and I would like to make a method call, that returns an Observable, sync. 我是RxJava的新手,我想进行一个方法调用,该方法返回一个Observable,sync。

This is the method signature: 这是方法签名:

JsonObject login();

I tried something like this, but it didn't work: 我尝试过类似的方法,但是没有用:

public JsonObject login() {
    return eventBus
    .sendObservable(...)
    .toBlocking().first().body();
}

How can I make it work? 我该如何运作?

Thank you. 谢谢。

Observable by design is Synchronous, if you want any operation Asynchronous you must use one of the specific operators.(onSubscribe, onObserver, buffer....) 从设计上可以观察到是“同步”,如果要进行任何“异步”操作,则必须使用特定的运算符之一。(onSubscribe,onObserver,buffer ....)

Also don't use toBlocking unless for your test, is almost an anti pattern, try to use the Observer pattern instead. 也不要使用toBlocking,除非您的测试几乎是一种反模式,请尝试使用Observer模式。

     public void main(String args[]){

         login().subscribe(jsonObject-> do Whatever you need);
     }


     public Observable<JsonObject> login() {
        return eventBus.sendObservable(...) --> I guess this call return an Observable
     }

If you want to take a look some basic examples take a look here https://github.com/politrons/reactive 如果您想看一些基本的例子,请看这里https://github.com/politrons/reactive

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM