RxTry


Source link: https://github.com/thuytrinh/RxTry

RxTry

Try<T> computation for RxJava

Usage

Go to JitPack. Then click Get it on the latest version.

What

Try<T> is a simple sum type representing 2 cases: success and failure.

val success = Success(1) success() // This will return 1.  val error = IllegalStateException() val failure = Failure(error) failure() // This will return the `error`.
val result = getResult() // Returns `Try<String>` when (result) {

is Success -> print(result())
is Failure -> logError(result()) 
}
fun getTop10NearbyRideShares(val position: Coordinates): Single<List<Ride>> {

return api.getRideShares(position = position, count = 10)
  .toTry() 
}

Corresponding Java usage via compose():

Single<List<Ride>> getTop10NearbyRideShares(final Coordinates position) {

return api.getRideShares(position, 10)
  .compose(toTrySingle()) 
}

Why

To produce a non-interrupted stream for RxJava

If you use Kotlin, this library provides 2 extension functions toTry() so that you can compose with Single or Observable.

Example

Whenever the user moves to a new location, you will ask PokémonService to retrieve top 10 nearby pokémons. Under the hood, PokémonService will shoot a network request to a RESTful backend service.

An initial impl can be like:

fun getTop10Pokemons(): Observable<List<Pokemon>> {

// Assume that you have `getUserLocationStream(): Observable<Location>`.
return getUserLocationStream()
  .switchMap(userLocation -> pokemonService.retrieveNearbyPokemons(count = 10)) 
}

But there's problem. If somehow retrieveNearbyPokemons() runs into network errors like, due to no Internet connection, or temporarily unreachable backend service, the stream returned by getTop10Pokemons() will be terminated. For example,

  • When the user moves to (1, 2), we got pokemons A, and B from pokemonService.
  • When the user moves to (2, 3), pokemonService fails due to IOException. The stream Observable<List<Pokemon>> triggers its onError(), thus terminates.
  • Next, when the user moves to (4, 5), we receive no event from getTop10Pokemons() anymore because it already terminated before.

So, using toTry() can solve the problem here:

fun getTop10Pokemons(): Observable<Try<List<Pokemon>>> {

// Assume that you have `getUserLocationStream(): Observable<Location>`.
return getUserLocationStream()
  .switchMap(userLocation -> {

 pokemonService.retrieveNearbyPokemons(count = 10)

// Assume that `isKindOfNetworkError()` is an extension function

// in form of `(Throwable) -> Boolean`.

.toTry {
 it.isKindOfNetworkError() 
}

  
}
) 
}

How can it be used from the outside?

getTop10Pokemons()
.subscribe {

  when (it) {

 is Success -> showPokemons(it())

 is Failure -> showError(it())
  
}

}

But how can toTry() actually be helpful? Let's go through the emission again:

  • When the user moves to (1, 2), we got pokemons A, and B from pokemonService, and they are wrapped into a Success.
  • When the user moves to (2, 3), pokemonService fails due to IOException. toTry() will wrap the error into a Failure. But actually getTop10Pokemons() won't terminate at all. The Failure will be emitted via onNext().
  • Next, when the user moves to (4, 5), we got pokemons C, and D from pokemonService. getTop10Pokemons() will continue to emit them via a Success again.

To separate anticipated errors from unexpected errors

Anticipated errors will be emitted via onNext() with Failure while onError() is the place dedicated for unexpected errors. Some example of the 2 kinds of error:

  • Anticipated errors: network errors (e.g. no Internet connection, temporarily unreachable backend service), validation errors (e.g. wrong email format).
  • Unexpected errors: Mostly due to programmer mistake for example.
// With `Try<T>` getTop10Pokemons()
.subscribe({

  when (it) {

 is Success -> showPokemons(it())

 // showError() will handle anticipated errors.

 is Failure -> showError(it())
  
}

}
, {

  // Unexpected errors will be reported to Crashlytics
  // for further investigation.
  logErrorViaCrashlytics(it)

}
)

vs.

// Without `Try<T>`. Everything goes into `onError()`. getTop10Pokemons()
.subscribe({

  showPokemons(it)

}
, {
 error ->
  when (error) {

 is NoInternetConnectionError -> showNoInternetConnectionError(error)

 is UnreachableServerError -> showUnreachableServerError(error)

 else -> logErrorViaCrashlytics(error)
  
}

}
)

Resources

This project is inspired by the Live Video Reactions on Facebook. I have used RxJava2 for handling the stream of reactions (like, love, haha, wow, sad, angry). I have put one extra condition that the time duration between two reactions should be atleast 300 ms.. This is achieved very easily by RxJava by using Flowable. Also, I have used Canvas to draw bitmaps over it and perform animations on top of it.

RxJava2 EventBus that supports pausing and resuming. This way, you can achieve that the bus is queueing events while it is paused and emitting events while it is resumed which is a nice way to enforce that events are only observed, when for example your activity is resumed and your views are accessible.

This project is for downloading items(songs, images etc) in Android using RxJava2. There are, however 2 conditions which I have set for downloading.

1) Only 2 items can be downloaded at a time. So even if the user clicks multiple items to download, only 2 of them will be actually downloaded at a time and the rest of the downloads will be en queued.

2) The download percent is shown to the user. But only if the difference between the current percentage and the previously shown percentage is greater than 5 percent.

FastHub is yet another open source GitHub client app but unlike any other app, FastHub built from ground up.

CircleMenu is a simple, elegant menu with a circular layout.

A fast, light-weight and powerful Play Store information fetcher for Android.

This library allows you to fetch various live information from Play Store of your app or any other app of your choice. With just a few lines of code, you can get access to a lot of useful app data fetched fresh from the Play Store.

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