mercredi 20 janvier 2021

Is there a way to share async code between classes in java (Android)?

Let's say I have two classes A and B.

public class myClassA {
  private void asyncMethodA(String url){
     Observable.fromCallable((Callable<Void>) () -> null //common part of the code
        ).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Void>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull Void aVoid) {
                 someACode();
                //This part is different for each class
            }


            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
  }
}


public class myClassB {
  private void asyncMethodB(String url){
     Observable.fromCallable((Callable<Void>) () -> null //common part of the code
        ).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Void>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull Void aVoid) {
                someBCode();
                //This part is different for each class
            }


            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
  }
}

Is it possible to have some sort of code that will help me not repeat the common part for each individual class? If so how do I implement it? It is necessary that the code will be asynchronous, so it won't lock the UI.

Aucun commentaire:

Enregistrer un commentaire