AndroidRX - run method in background

前端 未结 5 1775
独厮守ぢ
独厮守ぢ 2021-02-12 15:38

I created simple activity with infinity progres bar, and I\'am trying to run time consuming method using RxJava to prevent UI thread from blocking, but everytime UI thread is bl

5条回答
  •  猫巷女王i
    2021-02-12 16:16

    With RxJava2 a possible solution is:

    Version with lambdas:

    Single.fromCallable(() -> loadInBackground())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe((resultObject) -> { updateUi(resultObject) });
    

    Version without lambdas:

    Single.fromCallable(new Callable() {
        @Override
        public Object call() throws Exception {
            return loadInBackground();
        }
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Consumer() {
        @Override
        public void accept(Object resultObject) throws Exception {
            updateUi(resultObject);
        }
     });
    
    
    

    Example methods used above:

    private Object loadInBackground() {
        // some heavy load code
        return resultObject;
    }
    
    private void updateUi(Object resultObject) {
        // update your Views here
    }
    

    提交回复
    热议问题