Anuj Mody
Anuj Mody

Reputation: 525

Do background tasks using rxjava2

I have just started learning RxJava2. In my app, I want to query firebase and store some data in a database. The thing is I am confused on how should I use this with RxJava.Please if u can provide me with a start so that I can work on it. I found out there are many solutions so I am confused on what to use and when. I tried using a Single operator which will emit either success or failure but stuck in halfway.

Upvotes: 1

Views: 2575

Answers (1)

Dany Pop
Dany Pop

Reputation: 3658

This is how i use it : First, i create an abstract class :

public abstract class AsyncCommand<T> {


    public ObservableEmitter<T> mSubscriber;

    public ObservableEmitter<T> getSubscriber() {
        return mSubscriber;
    }

    public abstract T run() throws Exception;

    public Observable<T> returnObservable() {
        return Observable.create(
                new ObservableOnSubscribe<T>() {
                    @Override
                    public void subscribe(ObservableEmitter<T> subscriber) throws Exception {
                        mSubscriber = subscriber;
                        try {
                            subscriber.onNext(run());
                            subscriber.onComplete();
                        } catch (Exception e) {
                            subscriber.onError(e);
                        }
                    }
                }
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
}

and, Util.doesHostExist(mEmail) will be executed in io thread in this sample :

class VerifiyEmailDomain extends AsyncCommand<Boolean> {
    private final Context mContext;
    private final String mEmail;

    public VerifiyEmailDomain(Context context, String email) {
        mContext = context;
        mEmail = email;
    }

    @Override
    public Boolean run() throws Exception {
        return Util.doesHostExist(mEmail);
    }
}

To use it :

verifiyEmailDomain(context, email).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean result) throws Exception {
                 //do stuff in normal case
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
               // do stuff if exception occurs
            }
        });

Upvotes: 1

Related Questions