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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With