How to return fusedLocationProviderClient().lastLocation as flow from a function in kotlin coroutines

1.6k Views Asked by At

What i am doing

So i am developing a weather forecast application in which i am accessing the device location using fusedLocationProviderClient.lastLocation and most of us knows that the location provider return a task, so for that i am using coroutines Deferred so that whenever the task got completed it gives me the device location please have a look upon the code for better understanding

private fun getLastDeviceLocation(): Deferred<Location?> {
        return if (hasLocationPermission())
            fusedLocationProviderClient.lastLocation.asDeferred()
        else
            throw LocationPermissionNotGrantedException()
    }

What my problem is

but now i want my location to be a live location so for that i have to use coroutines flow, so that whenever my location changes i'll be able to fetch weather for the new location automatically, but because i am new to kotlin coroutines i am not sure how to achieve that and how i can be able to use flow with deferred,

can anyone please help me out or if this is not feasible do suggest me some other work aroung to achieve my goal Thanks in Advance

1

There are 1 best solutions below

3
On

If you want to convert Deferred to Flow:

val lastLocationFlow: Flow<Location> = flow {
    emit(fusedLocationProviderClient.lastLocation.asDeferred().await())
}

flow is the most basic flow builder. It takes a suspendable block as a parameter, that's responsible for emitting values. Deferred.await() will suspend execution until the task returns a Location (or null). The flow will then emit the value and finish.


If you want to convert requestLocationUpdates from callback to Flow, you could use callbackFlow.