Search code examples
androidandroid-asynctaskrx-javarx-android

RxAndroid with parameterized AsyncTask


I want to rewrite project using rxAndroid. In my code i have this simple part:

public void chkLogin(String login, String password) {
    String[] myTaskParams = { login, password };
    new ChkLoginTask().execute(myTaskParams);
}

private class ChkLoginTask extends AsyncTask<String, Void, LoginStatus> {
    @Override
    protected void onPreExecute(){
        view.showLoadingSpinner();
    }

    @Override
    protected LoginStatus doInBackground(String... params) {
        return app.getAPI().checkLogin(params[0], params[1]);
    }

    @Override
    protected void onPostExecute(LoginStatus result) {
        view.hideLoadingSpinner();
        if(result == null)
            view.onConnectionError();
        else{
            view.onChkLoginSuccess(result);
        }
    }
}

In this code i just call my api method in AsyncTask with two params and then react by view on it's result.

Now I want to write this code using rxAndroid, but I'm stuck on it... I know how rx work with react on UI elements, but can't find information about how it works with parameterized AsyncTask

And does it correct to use RX in this case?


Solution

  • Since you want to use RxJava, you don't need AsyncTask any more. You can rewrite your codes using subscribeOn and observeOn like this:

    public void chkLogin(String login, String password) {
        view.showLoadingSpinner();
        Observable.defer(() -> Observable.just(app.getAPI().checkLogin(login, password)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    view.hideLoadingSpinner();
                    if (result == null)
                        view.onConnectionError();
                    else {
                        view.onChkLoginSuccess(result);
                    }
                }, e -> {
                    // handle the exception
                });
    }