Android

Android AsyncTask => RxJava

Machine_웅 2023. 9. 5. 17:33
728x90
반응형
package com.gitsn.android.prism.Utilities;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public abstract  class GS_AsyncTask <T1,T2>  {

    /*
    * 사용 예시
    *         new GS_AsyncTask<String,String>(){
            @Override
            protected void onPreExecute() {

            }

            @Override
            protected String doInBackground(String arg) {
                return null;
            }

            @Override
            protected void onPostExecute(String result) {

            }
        }.execute("TEST");
    * */

    T1 mArgument;  // Argument

    T2 mResult; // Result

    // Execute
    final public void execute(final T1 arg) {
        // Store the argument
        mArgument = arg;
        // Call onPreExecute
        onPreExecute();
        // do Background
        Observable.fromCallable(()->{
            return doInBackground(arg);
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<T2>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull T2 t2) {
                        mResult = t2;

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        // Call onPostExecute
                        onPostExecute(null);
                    }

                    @Override
                    public void onComplete() {
                        // Call onPostExecute
                        onPostExecute(mResult);
                    }
                });


    }

    // onPreExecute
    protected abstract void onPreExecute();

    // doInBackground
    protected abstract T2 doInBackground(T1 arg);

    // onPostExecute
    protected abstract void onPostExecute(T2 result);
}
728x90
반응형