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
If you want to convert
Deferred
toFlow
: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 aLocation
(ornull
). The flow will then emit the value and finish.If you want to convert
requestLocationUpdates
from callback toFlow
, you could usecallbackFlow
.