Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object becomes null outside of callback function

Tags:

java

android

I have a callback function whose result I save in a class variable, like this:

public class MyClass {

    private double myDouble;
    private MyObject myObject;

    public myMethod() {

        AnotherObject anotherObject = new AnotherObject();        
        anotherObject.getInfo(new Callback<String>() {
            @Override
            public void success(MyObject myObject) {
                MyClass.this.myObject = myObject; // I save myObject inside the class variable myObject
                Log.d("LOG", "Value of myObject " + MyClass.this.myObject);

            }

            // a method for the failure case
        });
        Log.d("LOG", "Value of myObject " + MyClass.this.myObject);

    }
}

The first log message gives me the correct value, by which I suppose that the class variable myObject correctly stored the object value. However, the second log message, right outside the success function, returns null.

How can I get the correct object value also outside the callback function?

like image 317
user1301428 Avatar asked Jun 07 '26 01:06

user1301428


2 Answers

This is a callback, i.e. asynchronous in nature. You can't know when the success() method will be called and the assignment to myObject probably happens after checking it's value. Make sure you call Log.d() after the callback has completed.

like image 192
Filkolev Avatar answered Jun 09 '26 14:06

Filkolev


You are assuming that the callback passed to getInfo() will be executed immediately upon its return. Given your observed behavior, that is not the case. The callback is actually being invoked some time after getInfo() returns.

Sometimes callbacks are called immediately, but in this case not. Many callbacks are invoked by work done in another thread, and in those cases, the thread invoking getInfo() is simply continuing on while the other thread does some computation. When you have a callback like that that is not guaranteed to be invoked immediately, you should only refer to its results in the callback itself, or some time after the callback is invoked.

like image 40
Doug Stevenson Avatar answered Jun 09 '26 13:06

Doug Stevenson