Async Operation for Location return


#1

I’ve the below code to return location, but apparently the return is executed before the location be returned, how can I postpone it to ensure it return at the correct time:

import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import oryx.tecna.locateme.extensons.toast

private lateinit var fusedLocationClient: FusedLocationProviderClient

object UtilLocation {
    private lateinit var l : Location

    @SuppressLint("MissingPermission")
    fun getLocation(context: Context) : Location{
        context.toast("mlocation is called")
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)

        fusedLocationClient.lastLocation
                .addOnSuccessListener { location : Location? ->
                    this.l = location!!
                  //  context.toast("my location is: ${location?.latitude}")
                }
       return this.l
    }
}

#2

You can block thread using, for example, a Guava SettableFuture.

Otherwise you can suspend routine execution, but this way is a bit harder to understand