RxLocation


Source link: https://github.com/patloew/RxLocation

Reactive Location API Library for Android

This library wraps the Location APIs in RxJava 2 Observables, Singles, Maybes and Completables. No more managing GoogleApiClients! Also, the resolution of the location settings check is optionally handled by the lib.

For RxJava 1, please take a look at the Android-ReactiveLocation library by Micha? Charmas.

Usage

Create an RxLocation instance once, preferably in your Application's onCreate() or by using a dependency injection framework. The RxLocation class is very similar to the classes provided by the Location APIs. Instead of LocationServices.FusedLocationApi.getLastLocation(apiClient) you can use rxLocation.location().lastLocation(). Make sure to have the Location and Activity Recognition permissions from Marshmallow on, if they are needed by your API requests.

Example:

// Create one instance and share it RxLocation rxLocation = new RxLocation(context);
  LocationRequest locationRequest = LocationRequest.create()

  .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)

  .setInterval(5000);
  rxLocation.location().updates(locationRequest)
.flatMap(location -> rxLocation.geocoding().fromLocation(location).toObservable())
.subscribe(address -> {

 /* do something */

}
);

The following APIs are wrapped by this library:

  • ActivityRecognition.ActivityRecognitionApi via rxLocation.activity()
  • LocationServices.FusedLocationApi via rxLocation.location()
  • LocationServices.GeofencingApi via rxLocation.geofencing()
  • LocationServices.SettingsApi via rxLocation.settings()
  • Geocoder via rxLocation.geocoding()

Checking the location settings is simplified with this library, by providing a Single<Boolean> via rxLocation.settings().checkAndHandleResolution(locationRequest), which handles showing the resolution dialog if the location settings do not satisfy your request. It returns true if the settings are satisfied (optionally after showing the dialog, if a resolution is possible), and false otherwise. If you want to handle the LocationSettingsResult yourself, you can do so via rxLocation.settings().check(locationRequest).

An optional global default timeout for all Location API requests made through the library can be set via rxLocation.setDefaultTimeout(...). In addition, timeouts can be set when creating a new Observable by providing timeout parameters, e.g. rxLocation.geofencing().add(geofencingRequest, pendingIntent, 15, TimeUnit.SECONDS). These parameters override the default timeout. When a timeout occurs, a StatusException is provided via onError(). Keep in mind that these timeouts only apply to calls to the Location API, e.g. when registering a location update listener. As an example, the timeout provided to rxLocation.location().updates(locationRequest, 15, TimeUnit.Seconds) does not mean that you will not receive location updates anymore after 15 seconds. Use setExpirationDuration() on your locationRequest for this use case.

Don't forget to dispose of your Subscriber/Observer when you are finished:

Disposable disposable = rxLocation.location().updates(locationRequest).subscribe();
  // Dispose of your Observer when you no longer need updates disposable.dispose();

As an alternative, multiple Disposables can be collected to dipose of at once via CompositeDisposable:

CompositeDisposable disposable = new CompositeDisposable();
 disposable.add(rxLocation.location().updates(locationRequest).subscribe());
  // Dispose of all collected Disposables at once, e.g. in onDestroy() disposable.clear();

You can also obtain a Flowable<GoogleApiClient>, which connects on subscribe and disconnects on dispose via GoogleApiClientFlowable.create(...).

The following Exceptions are thrown in the lib and provided via onError():

  • StatusException: When the call to the Location APIs was not successful or timed out
  • GoogleApiConnectionException: When connecting to the GoogleApiClient was not successful.
  • GoogleApiConnectionSuspendedException: When the GoogleApiClient connection was suspended.
  • SecurityException: When you try to call an API without proper permissions.
  • LocationSettingsNotSatisfiedException: When you use rxLocation.settings().checkAndHandleResolutionCompletable(...) and the location settings were not satisfied, even after handling the resolution.

When using the Geocoding component of RxLocation, exceptions can be thrown even after disposing, which can lead to app crashes. To prevent this, install a global RxJavaPlugins.setErrorHandler(), e.g. in your Application class.

Sample

A basic sample app is available in the sample project.

Setup

The lib is available on jCenter. Add the following to your build.gradle:

dependencies {

  compile 'com.patloew.rxlocation:rxlocation:1.0.3' 
}

Testing

When unit testing your app's classes, RxLocation behavior can be mocked easily. See the MainPresenterTest in the sample project for an example test.

Credits

The code for managing the GoogleApiClient was adapted from the Android-ReactiveLocation library by Micha? Charmas, which is licensed under the Apache License, Version 2.0.

License

Copyright 2016 Patrick Löwenstein  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

Resources

Reactive wrapper around Android's FileObserver.

Android Library to easily allow you to determine device's WebGL support level.

It's a tracking activity ring widget like in Apple watch for Android.

A different beautiful Floating Edit Text.

JsonAnnotation can speed up Android development. It generates gson model class by json string automatically and lets you concentrate on what's really important.

The library allows to create fixed collage (cards can not be moved, scaled or rotated) or dynamic collage (cards can move, scale and rotate).

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes