子线程获取返回值问题

   String string = "3";
//
        int i = getString(string);
//
        Log.d(TAG, "ExampleUnitTest.synaized." + i);
    }

    public  int getString(String s) {
        final int[] i = {0};
        Observable.just(s)
                .map(new Function() {
                    @Override
                    public Integer apply(@NonNull String s) throws Exception {
                        return Integer.parseInt(s);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
            @Override
            public void accept(@NonNull Integer integer) throws Exception {
                i[0] = integer;
                Log.d(TAG, "ExampleUnitTest.accept." + i[0]);
            }
        });
        Log.d(TAG, "ExampleUnitTest.getString." + i[0]);
        return i[0];
    }

打印参数

 D/MapActivity: ExampleUnitTest.getString.0
D/MapActivity: ExampleUnitTest.synaized.0
D/MapActivity: ExampleUnitTest.accept.3

如果你要是开启了子线程他就不会阻塞方法的执行继续往下走,想利用拿到回调里的参数只能在回调里进行参数的设置了;

  String string = "3";
//
        int i = getString(string);
//
        Log.d(TAG, "ExampleUnitTest.synaized." + i);
    }

    public  int getString(String s) {
        final int[] i = {0};
        Observable.just(s)
                .map(new Function() {
                    @Override
                    public Integer apply(@NonNull String s) throws Exception {
                        return Integer.parseInt(s);
                    }
                })
                .subscribe(new Consumer() {
            @Override
            public void accept(@NonNull Integer integer) throws Exception {
                i[0] = integer;
                Log.d(TAG, "ExampleUnitTest.accept." + i[0]);
            }
        });
        Log.d(TAG, "ExampleUnitTest.getString." + i[0]);
        return i[0];
    }

打印结果

 ExampleUnitTest.accept.3
 D/MapActivity: ExampleUnitTest.getString.3
 D/MapActivity: ExampleUnitTest.synaized.3
虽然你走了回调,但是他还是在一个线程中,所以方法按顺序执行,先走回调然后走方法的返回值,然后拿到方法的返回值;

你可能感兴趣的:(子线程获取返回值问题)