0

I am trying to pass a function to an Async class, that function suppose to return a result to the calling activity, my best try so far is the following code.

The problem with this is that I defined result on top so it will be accessible by OnEventCompleteCallBack function, but in the same time I am returning it to the calling activity, it doesn't sound right.

Also, my code involved calling two function to get back the results I need. Is there a better way of achieving this?

Ideally I would like to pass the Function functionIWouldLikeToPass to the Async, but I read that this is not possible in Java (contrary to C#).

My Activity:

Private MyOtherClass result;

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //....
        myResult = getResultAsync(str);
        //...   
    }

    public MyOtherClass functionIWouldLikeToPass(MyClass myClass){

    //do stuff with myClass
    //return MyOtherClass type to the result call to the activity
    }

    public MyOtherClass getResultAsync(String str) {

        new AsyncTask_GetSingeValue(new IOnEventCompleteCallBack() {

            @Override
            public void OnEventCompleteCallBack(MyClass asyncResult) {
                result= functionIWouldLikeToPass(asyncResult);
            }
        }).execute(str);

        return result;

    }
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
masood elsad
  • 434
  • 2
  • 6
  • 18
  • At first glance, and assuming not using Java8, which provides `Action` and `Function` classes, I would suggest looking into RetroLambda and/or RxJava – OneCricketeer Sep 03 '17 at 02:15
  • `getResultAsync` must be `void`, otherwise you are immeadiately returning null because `.execute(str);` is not a blocking call – OneCricketeer Sep 03 '17 at 02:19
  • Probably the simplest solution is to pass an instance of your activity to the AsyncTask constructor. This means you should create an instance of your AsyncTask subclass directly rather than creating an anonymous inner class which subclasses your AsyncTask subclass. – Code-Apprentice Sep 03 '17 at 02:44
  • Thanks all. I contiued using the Interface, but not passing any vales back to the onCreate. I do what I needed to do in the onCreate inside the functionIWouldLikeToPass instead, and worked :) – masood elsad Sep 03 '17 at 03:00

0 Answers0