Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refine flow structure #9

Merged
merged 1 commit into from Nov 17, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
}
}