美文网首页
Java将异步调用转换为同步调用

Java将异步调用转换为同步调用

作者: 风云不羁 | 来源:发表于2019-05-04 11:17 被阅读0次

    调用外部的Api时,根据自己业务需求有时需要同步调用,如果这些Api没有提供同步调用的方法,此时该如何转同步调用呢

    下面提供一种Java中的实现方式:

    public class AsyncCallback {
        private Boolean finished = null;
    
        public AsyncCallback call() {
            new Thread() {
                @Override
                public void run() {
                    synchronized (AsyncCallback.this) {
                        try {
                            Thread.sleep(3000);
    
                            finished = true;
                        } catch (InterruptedException ignore) {
                            finished = false;
                        }
                        AsyncCallback.this.notifyAll();
                    }
                }
            }.start();
    
            return this;
        }
    
        public boolean isFinished() {
            synchronized (this) {
                while (finished == null) {
                    try {
                        wait();
                    } catch (InterruptedException ignore) {
                    }
                }
            }
    
            return finished;
        }
    
        public static Observable<Boolean> asyncCall() {
            return Observable.defer(new Callable<ObservableSource<? extends Boolean>>() {
                @Override
                public ObservableSource<? extends Boolean> call() throws Exception {
                    return Observable.just(new AsyncCallback().call().isFinished());
                }
            });
        }
    
        @SuppressLint("CheckResult")
        public static void testAsync2Sync() {
            asyncCall().subscribeOn(Schedulers.computation())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            Log.e("HTTP-LOG", "start call sync method");
                        }
                    })
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            Log.e("HTTP-LOG", "sync call returned, " + aBoolean);
                        }
                    });
        }
    

    通过这样的转换,就可以将异步接口转换为同步调用

    相关文章

      网友评论

          本文标题:Java将异步调用转换为同步调用

          本文链接:https://www.haomeiwen.com/subject/fykxoqtx.html