+2 votes
13 views

(Disclaimer: There are a ton of questions which arise from people asking about data being null/incorrect when using asynchronous operations through requests such as facebook,firebase, etc. My intention for this question was to provide a simple answer for that problem to everyone starting out with asynchronous operations in android)

I'm trying to get data from one of my operations, when I debug it using breakpoints or logs, the values are there, but when I run it they are always null, how can I solve this ?

Firebase

firebaseFirestore.collection("some collection").get()
    .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot documentSnapshots) {
            //I want to return these values I receive here... 
        });
//...and use the returned value here.

Facebook

GraphRequest request = GraphRequest.newGraphPathRequest(
    accessToken,
    "some path",
    new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse response) {
            //I want to return these values I receive here...
        }
    });
request.executeAsync();
//...and use the returned value here.

Kotlin coroutine

var result: SomeResultType? = null
someScope.launch {
    result = someSuspendFunctionToRetrieveSomething()
    //I want to return the value I received here... 
}
Log.d("result", result.toString()) //...but it is still null here.

Etc.

Please log in or register to answer this question.

...