Created
March 3, 2018 05:34
-
-
Save bgogetap/b2889357466a01990d374641ceda36bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.annotation.SuppressLint | |
import android.content.Context | |
import android.os.Looper | |
import com.google.android.gms.location.LocationCallback | |
import com.google.android.gms.location.LocationRequest | |
import com.google.android.gms.location.LocationResult | |
import com.google.android.gms.location.LocationServices | |
import com.google.android.gms.maps.model.LatLng | |
import io.reactivex.BackpressureStrategy | |
import io.reactivex.Flowable | |
import io.reactivex.disposables.Disposables | |
import javax.inject.Inject | |
import javax.inject.Singleton | |
/** | |
* Class that keeps track of all location updates while the Application is running. | |
*/ | |
@SuppressLint("MissingPermission") | |
@Singleton | |
class LocationService @Inject constructor(private val context: Context) { | |
val locationUpdateStream: Flowable<LocationPoint> = Flowable.create<LocationPoint>({ emitter -> | |
val client = LocationServices.getFusedLocationProviderClient(context) | |
val locationCallback = object : LocationCallback() { | |
override fun onLocationResult(locationResult: LocationResult?) { | |
locationResult?.lastLocation?.let { location -> | |
if (!emitter.isCancelled) { | |
emitter.onNext(LocationPoint( | |
location = LatLng(location.latitude, location.longitude), | |
time = location.time, | |
speed = location.speed.toDouble(), | |
accuracy = location.accuracy.toDouble())) | |
} | |
} | |
} | |
} | |
client.requestLocationUpdates(LocationRequest.create().apply { | |
priority = LocationRequest.PRIORITY_HIGH_ACCURACY | |
interval = 1000 | |
fastestInterval = 500 | |
smallestDisplacement = 1.0f | |
}, locationCallback, Looper.getMainLooper()) | |
if (!emitter.isCancelled) { | |
emitter.setDisposable(Disposables.fromAction { | |
client.removeLocationUpdates(locationCallback) | |
}) | |
} | |
}, BackpressureStrategy.LATEST) | |
.share() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment