mardi 28 mai 2019

Is there a way to invoke a generic method from an async thread?

In order to avoid boilerplate, and handling a very specific SDK with customised API transactions, I would try to pass on a generic method, that would be invoked and executed asynchronously.

I have tried using RxJava, the EventBus and AsyncTask. However, whenever it would get there, I would always get a android.os.NetworkOnMainThreadException.

I did use an interface, which obviously works perfectly fine, but I was wondering why can't the same apply to a generic method? Is it because I don't specifically send the whole object on the new thread?

If I would send an instance of an object, then, given that each method has a different name, it would not be convenient invoking the specific method (unless the name was passed on as a String, perhaps?).

The code that would run on the new thread would be a variation of the following:

public <T> void invokeMethod(T item) throws InvocationTargetException, IllegalAccessException {
        if (item instanceof Method) {
            ((Method) item).invoke(this, (Object[]) null);
        }
    }

Obviously, usually methods run properly when I do that, but they are always executed on the main thread.





Aucun commentaire:

Enregistrer un commentaire