zyzz777
zyzz777

Reputation: 37

Return from function inside a called method

I wanna know if it's possible to return a value from a function that is contained inside a called method.

This method is getting an html page source code so it can get time to return a value.

But the time isn't the problem here (or maybe it can be).

protected boolean booleanLinkReturn(String link) {
    boolean ret = false;

    Ion.with(getApplicationContext()).load(link).asString().setCallback(new FutureCallback<String>() {
        @Override
        public void onCompleted(Exception e, String result) {
            ret = true;
            /*
             if I set "ret" here (I can't do btw because it needs to be declared final)
             the function will return always false
             p.s. I have to do more things here not only the boolean
            */
        }
    });

    return ret;
}

there is a way to return the boolean in base at the result of the code inside the method?

Upvotes: 0

Views: 236

Answers (2)

payloc91
payloc91

Reputation: 3809

This is why you are given the chance to use a callback. You don't know when you will get a response (and if you ever will), and the callback is a way to execute code in response to an event.


In your case, given you really need to know whether the link was opened, you can change your strategy and have the callbacks act on field-members variables, which are allowed to be modified by anonymous classes / lambdas.

This is just a generic draft: adapt it to your case.

class LinkOpenerAttempt {
    private boolean returned = false;
    private final String link;
    private final Context context;

    private final FutureCallback<String> returnCallback = new FutureCallback<String>() {
        @Override
        public void onCompleted(final Exception e, final String result) {
            LinkOpenerAttempt.this.returned = true;
        }
    };

    public LinkOpenerAttempt(final Context context, final String link) {
        this.link = link;
        this.context = context;
    }

    public void execute() {
        Ion.with(this.context)
                .load(link)
                .asString()
                .setCallback(this.returnCallback);
    }

    public boolean isReturned() {
        return this.returned;
    }
}

You may want to mark the variable as volatile if you have reason to believe the callback will be executed on a different thread.

You can also declare the Callback within the activity and pass it to the class.

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93678

No, because the function isn't being called now. Its being called at some future time (or not called ever is also a possibility). There's no way to return that value, because it hasn't been calculated yet, and may never be.

The correct way to do this is to make all the code that needs to be run with that value known either placed in onCompleted, or called from there via another callback function.

Upvotes: 2

Related Questions