Skip to content

Commit

Permalink
Merge pull request #9 from Jintin/feature/flow_refine
Browse files Browse the repository at this point in the history
Refine flow structure
  • Loading branch information
Jintin committed Nov 17, 2020
2 parents 1d94488 + dbe4302 commit ac3df9e
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions lib/src/main/java/com/jintin/fancylocation/LocationFlow.kt
Expand Up @@ -15,34 +15,32 @@ import kotlinx.coroutines.runBlocking
@ExperimentalCoroutinesApi
class LocationFlow(
private val locationProvider: ILocationProvider
) : ILocationObserver {
) {

constructor(
context: Context,
locationRequest: LocationRequest
) : this(LocationProvider(context, locationRequest))

private var sendChannel: SendChannel<LocationData>? = null

@RequiresPermission(anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION])
fun get(): Flow<LocationData> = channelFlow {
locationProvider.requestLocationUpdates(this@LocationFlow)
sendChannel = this.channel
locationProvider.requestLocationUpdates(object : ILocationObserver {
override fun onLocationResult(location: Location) {
setValue(channel, LocationData.Success(location))
}

override fun onLocationFailed() {
setValue(channel, LocationData.Fail)
}

})
awaitClose {
sendChannel = null
locationProvider.removeLocationUpdates()
}
}

private fun setValue(value: LocationData) = runBlocking {
sendChannel?.send(value)
}

override fun onLocationResult(location: Location) {
setValue(LocationData.Success(location))
}

override fun onLocationFailed() {
setValue(LocationData.Fail)
}
private fun setValue(sendChannel: SendChannel<LocationData>, value: LocationData) =
runBlocking {
sendChannel.send(value)
}
}

0 comments on commit ac3df9e

Please sign in to comment.