nearby restaurants fit for the logged in user • we need to fetch the user data from DB • get the current location • then fetch nearby stores • so we have 3 async calls to execute
data streams.”, GitHub • everything can be a stream of data : location, DB entries, current user, shopping cart, etc. • streams can be combined, transformed and the resulting stream observed by subscribers
• fetch Tweets by @droidconRO • fetch Tweets with #droidconro hashtag • do this in parallel • deliver final results to UI • should we first imagine this in Java, without RX ?
want DB storage • implement a repository for Tweets • first fetches items from DB • then fetches new items from API • stores API items in DB • deliver both results to the UI as they arrive
need to write our own Observable • more advanced, must know what you doing • use Observable.create( subscriber ) • connect to the service / client ( eg: location) • emit data as it arrives via subscriber.onNext(data) • disconnect from the service / client when the subscription is disposed
hunter Location • continuously track hunter compass • poll other hunters location from API every 5 seconds • check if hunter direction intersects other hunters • alarm user
Observable.combineLatest( getLocation(), getOrientation(), huntersObservable, Function3 { location: Location, azimuth: Double, hunters: List<Hunter> -> //Check if hunter direction intersects other nearby hunters checkHuntersIntersection(location, azimuth, hunters) }) PASS DATA TO A FUNCTION THAT CHECKS IF WE INTERSECT ANY OTHER HUNTER
Observable.combineLatest( getLocation(), getOrientation(), huntersObservable, checkHuntersIntersection()) //... fun checkHuntersIntersection() = Function3 { loc: Location, azimuth: Double, hunters: List<Hunter> -> //...check if hunter direction intersects other nearby hunters true } SIMPLIFIED, EXTRACTED TO A METHOD RETURNING A FUNCTION
Observable.combineLatest( getLocation(), getOrientation(), huntersObservable, checkHuntersIntersection()) .subscribe({ inDanger -> if (inDanger) alarmUser() }) IN THE END, SUBSCRIBE TO THE RESULT
returns a Subscription • keep a reference to it, and call dispose() • unsubscribes from all observables (location,orientation,etc) val subscription = Observable.combineLatest( //... .subscribe({ //... }) subscription.dispose()
simpler to do “async” / “threaded” work • complex threading becomes very easy • a lot of operators and adapters • async code more expressive and clean • easy to test • RXJava, RXAndroid, RXSwift, RXJS, RXNet ...
not easy to understand • easy to make mistakes and missuse • not handling subscriptions, can lead to memory leaks • might get hard to onboard people on projects using RX