In the past, I have used AsyncTasks to perform network requests for my Android app. I recently switched to RxJava to be able to cancel the requests when the user exits an activity. I have created a system to easily create new async tasks via RxJava which all cancel when a user exits an activity. I have attached some basic code that I hope somebody could give me some pointers on.
public class BaseActivity extends AppCompatActivity{
ArrayList<OnDestroyListener> listeners = new ArrayList<>();
@Override
protected void onDestroy() {
for(OnDestroyListener listener : listeners){
listener.onDestroy();
}
super.onDestroy();
}
public void addOnDestroyListener(OnDestroyListener listener){
listeners.add(listener);
}
public interface OnDestroyListener{
void onDestroy();
}
}
public class Tools{
public static <E> void observe(Callable<E> callable, SingleSubscriber<E> subscriber, BaseActivity activity){
final Subscription sub = Single.fromCallable(callable)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
if(activity == null){
return;
}
activity.addOnDestroyListener(new BaseActivity.OnDestroyListener() {
@Override
public void onDestroy() {
sub.unsubscribe();
}
});
}
}
public class Endpoint{
public void makeGetRequestAsync(final String url, final SingleSubscriber<String> subscriber, BaseActivity activity){
Tools.observe(new Callable<String>() {
@Override
public String call() throws Exception {
return makeGetRequestSync(url);
}
}, subscriber, activity);
}
}
public class SampleActivity extends BaseActivity{
Endpoint endpoint = new Endpoint();
void onButtonClick(View v){
endpoint.makeGetRequestAsync("https://someurl.com", new SingleSubscriber<String>() {
@Override
public void onSuccess(String result) {
//Request success
}
@Override
public void onError(Throwable error) {
//Request failure
}
}, this);
}
}
I know that I do not have a real coding problem, since this method has been working very well so far, but I just want to know if anything about this process is inherently wrong, as I am using it throughout my app.