我试图使用netflix observable,但我设法只是同步:
这就是我定义远程调用的方式:
@Named
public class BroConsumerService {
..
@HystrixCommand(fallbackMethod = "stubbedMethod")
public Observable<String> executeObservableBro(String name) {
return new ObservableResult<String>() {
@Override
public String invoke() {
return executeRemoteService(name);
}
};
}
private String stubbedMethod(String name) {
return "return stubbed";
}
//这里我实际上正在调用(并观察此方法)
@RequestMapping("/executeObservableBro")
public String executeObservableBro(@RequestParam(value = "name", required = false) String name) throws ExecutionException, InterruptedException {
Observable<String> result= broConsumerService.executeObservableBro(name);
result.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
System.out.println("completed");
}
@Override
public void onError(Throwable e) {
System.out.printf(e.getMessage());
}
@Override
public void onNext(String s) {
System.out.println("on next..");
}
});
}
但是同步工作。我想在执行之前能够“监听”executeObservableBro。并且每次执行时都会得到通知。
示例将受到高度赞赏。
谢谢, 射线。
答案 0 :(得分:0)
您必须在subscribeOn方法中提供调度程序,如:
public static void main(String[] args) throws InterruptedException {
Observable<Integer> observable2 = Observable.create(subscriber->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Arrays.asList(1, 2, 3).forEach((value)-> subscriber.onNext(value));
subscriber.onCompleted();
subscriber.onError(new RuntimeException("error"));
});
System.out.println("Before");
observable2
.subscribeOn(Schedulers.io()).subscribe(
(next) -> log.info("Next element {}", next),
(error) -> log.error("Got exception", error),
() -> log.info("Finished")//on complete
);
System.out.println("After");
//Thread.sleep(5000); //uncomment this to wait for subscriptions, otherwise main will quit
}
默认情况下它不是异步的:)