SlideShare a Scribd company logo
1 of 27
Functional Reactive Android
(with Groovy)
Presentation Structure
● Who
● Why
● What
● How
Who
Carlos Anjos
Senior Android Developer @ Muzzley, an awesome IoT Startup
Handle: “${lastname}${firstname[0]}”
Email: “${handle}@gmail.com” or “${firstname}.${lastname}@muzzley.com”
More: “https://pt.linkedin.com/in/${handle}”
Why
● Technological reasons
● Human reasons
Tech reasons
Moore's law - the observation that
the number of transistors in a dense
integrated circuit doubles
approximately every two years
We’re moving to more cores ...
Human reasons
● Working memory only holds 7 +- 2 items at the same time
● But we’re able to use Chunking
“Chunking in psychology is a process by which individual pieces of information are
bound together into a meaningful whole (Neath & Surprenant, 2003)”
We need greater abstractions
“The power of the unaided mind is highly overrated. Without external aids,
memory, thought, and reasoning are all constrained. But human intelligence is
highly flexible and adaptive, superb at inventing procedures and objects that
overcome its own limits” - Donald Droman, in “Things that make us smart”
Examples:
Assembly -> Fortran -> C -> C++ -> Java -> Groovy -> ?
Traditional IT -> Iaas -> Paas -> Saas -> XaaS (microservices like Amazon
lambda, Google Cloud Functions)
Deep learning ...
What is Functional
f(x) = x + 2
int f(int x) { return x + 2 }
● Does not keep state
● For same input, always same output
● Everything the function needs is provided as a parameter
● Immutable:
○ Integer f(Integer x) { return new Integer(x.intValue() + 2) }
○ x.setInt(7)
Why functional
● Parallelization
● Microservices
● Readability
● Language Agnostic
What is Reactive
Reacts to events / Hollywood pattern
Iterator -> pull Observer -> push
interface Iterator<T> {
boolean hasNext();
T next();
}
interface Observer<T> {
onNext(T t);
onCompleted();
onError(Throwable e);
}
Why reactive
Easy Threading
No callback hell
Function composition
A ton of operators
Easier to reason about
Common vocabulary across languages and platforms (java, swift, etc)
Rx Example
// print every item in the array [1,2,3]
Observable.from(Arrays.asList(1,2,3)).subscribe(new Action1<Integer>() {
@Override
public void call(Integer i) {
System.out.println(i);
}
}); // in java
Observable.from(Arrays.asList(1,2,3)).subscribe((Integer i)->{ println(i) })//(Java 8)
Observable.from([1,2,3]).subscribe { println(it) } //(in Groovy)
Retrofit
@PATCH("/users/{userId}")
Observable<User> setUser(@Path("userId") String userId, @Body User user);
api.setUser(userPreference.getId(), newUserPatch)
.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(
{userPreference.save()},
{Timber.d(it,"Error sending new prefs async")}
)
RxAndroid
Observable.combineLatest(
ViewObservable.text(editGroupName),
adapter.getCurrentSelectedChannelObservable(),
{ OnTextChangeEvent onTextChangeEvent, List<String> selectedChannelIds -
>
onTextChangeEvent.text.length() > 0 && selectedChannelIds.size() >= 2
})
.subscribe { buttonNext.setEnabled(it)}
Tons of operators
latLngObservable.debounce(500, TimeUnit.MILLISECONDS).flatMap {
place.latitude = it.latitude
place.longitude = it.longitude
Observable.create(new GeocoderSubscriber(geocoder, it))
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe({
place.address = it
mAddress.setText(it);
}, { FeedbackMessages.showMessage(mAddress,"Error getting address") });
RxPermissions
RxPermissions.getInstance(getActivity())
.request(Manifest.permission.ACCESS_FINE_LOCATION)
.filter{it}
.flatMap { LocationSettings.getInstance(getActivity())}
.subscribe { println(it.isLocationUsable())}
Other Rx projects
RxMarbles
RxLifecycle
RxBus
Android-ReactiveLocation
What is Groovy
JVM language
Born in 2003
Inspired by Java, Python, Ruby, Perl, Smalltalk, Objective-C
“Superset” of java
Apache license
Dynamic by default, but also Static if you want to (and I do !)
Why groovy
Already using it for the build system (although Kotlin in the future ?)
Looks like java
Easier to transition to
Good IDE support
Much less verbose
Array and map literals, closures, null safe navigation
More functional
Apache Project and License
Closures, multiline string & interpolation, safe nulls
new AlertDialog.Builder(context)
.setMessage(Html.fromHtml("""
<small><font color='#$worker.categoryColor'>
${worker.category?.toUpperCase()}
</font></small><br /><br />
<b>${worker.devicesText}</b><br /><br />
${worker.description}<br /><br />
<font color='#99a7aa'>
<i>This is an advanced automation and cannot be edited</i></font>
"""))
.setPositiveButton("Got it", { DialogInterface dialog, int which -> gotIt()})
.show()
Switch and casts on steroids
Closure onAction(Object action){
switch (action){
case String: return {startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(action as String)))}
case Closure: return action as Closure
default: return {startActivity(new Intent(activity, action as Class))}
}
}
Much, much more ...
● Safe null navigation, boolean cohersion:
If (myObj?.myInnerCollection) { doStuff() }
groups?.each { group ->areas.find { it.id == group.parent }?.children?.add(group) }
● AST Transformations == Compile time meta-programming
@CompileStatic, @InheritConstructors, @EqualsHashCode, @ToString,
@Immutable, and many more
● Operator overloading
Groovy caveats
Debugger looses its bearings
Compiler sometimes gets confused when dealing with inner classes (in groovy)
Java preprocessors might not work (YMMV), although Dagger works fine
Questions ?
Thanks !

More Related Content

Similar to Functional reactive android (with Groovy)

Five android architecture
Five android architectureFive android architecture
Five android architectureTomislav Homan
 
Mining Fuzzy Time Interval Periodic Patterns in Smart Home Data
Mining Fuzzy Time Interval Periodic Patterns  in Smart Home Data    Mining Fuzzy Time Interval Periodic Patterns  in Smart Home Data
Mining Fuzzy Time Interval Periodic Patterns in Smart Home Data IJECEIAES
 
He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!François-Guillaume Ribreau
 
MongoDB Europe 2016 - Enabling the Internet of Things at Proximus - Belgium's...
MongoDB Europe 2016 - Enabling the Internet of Things at Proximus - Belgium's...MongoDB Europe 2016 - Enabling the Internet of Things at Proximus - Belgium's...
MongoDB Europe 2016 - Enabling the Internet of Things at Proximus - Belgium's...MongoDB
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GParsPaul King
 
Java y Ciencia de Datos - Java Day Ecuador
Java y Ciencia de Datos - Java Day EcuadorJava y Ciencia de Datos - Java Day Ecuador
Java y Ciencia de Datos - Java Day Ecuadorjorgaf
 
A comprehensive study of non blocking joining techniques
A comprehensive study of non blocking joining techniquesA comprehensive study of non blocking joining techniques
A comprehensive study of non blocking joining techniquesIAEME Publication
 
A comprehensive study of non blocking joining technique
A comprehensive study of non blocking joining techniqueA comprehensive study of non blocking joining technique
A comprehensive study of non blocking joining techniqueiaemedu
 
Software Sustainability: Better Software Better Science
Software Sustainability: Better Software Better ScienceSoftware Sustainability: Better Software Better Science
Software Sustainability: Better Software Better ScienceCarole Goble
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
How Secure Are Docker Containers?
How Secure Are Docker Containers?How Secure Are Docker Containers?
How Secure Are Docker Containers?Ben Hall
 
Data Management for Quantitative Biology - Database Systems (continued) LIMS ...
Data Management for Quantitative Biology - Database Systems (continued) LIMS ...Data Management for Quantitative Biology - Database Systems (continued) LIMS ...
Data Management for Quantitative Biology - Database Systems (continued) LIMS ...QBiC_Tue
 
Meetup rio
Meetup rioMeetup rio
Meetup riosuyograo
 
FIWARE Wednesday Webinars - Performing Big Data Analysis Using Cosmos With Sp...
FIWARE Wednesday Webinars - Performing Big Data Analysis Using Cosmos With Sp...FIWARE Wednesday Webinars - Performing Big Data Analysis Using Cosmos With Sp...
FIWARE Wednesday Webinars - Performing Big Data Analysis Using Cosmos With Sp...FIWARE
 
Possible Worlds Explorer: Datalog & Answer Set Programming for the Rest of Us
Possible Worlds Explorer: Datalog & Answer Set Programming for the Rest of UsPossible Worlds Explorer: Datalog & Answer Set Programming for the Rest of Us
Possible Worlds Explorer: Datalog & Answer Set Programming for the Rest of UsBertram Ludäscher
 
Smarter internet of things with stream and event processing virtual io_t_meet...
Smarter internet of things with stream and event processing virtual io_t_meet...Smarter internet of things with stream and event processing virtual io_t_meet...
Smarter internet of things with stream and event processing virtual io_t_meet...Istvan Rath
 

Similar to Functional reactive android (with Groovy) (20)

Five android architecture
Five android architectureFive android architecture
Five android architecture
 
Mining Fuzzy Time Interval Periodic Patterns in Smart Home Data
Mining Fuzzy Time Interval Periodic Patterns  in Smart Home Data    Mining Fuzzy Time Interval Periodic Patterns  in Smart Home Data
Mining Fuzzy Time Interval Periodic Patterns in Smart Home Data
 
He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!
 
MongoDB Europe 2016 - Enabling the Internet of Things at Proximus - Belgium's...
MongoDB Europe 2016 - Enabling the Internet of Things at Proximus - Belgium's...MongoDB Europe 2016 - Enabling the Internet of Things at Proximus - Belgium's...
MongoDB Europe 2016 - Enabling the Internet of Things at Proximus - Belgium's...
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GPars
 
Java y Ciencia de Datos - Java Day Ecuador
Java y Ciencia de Datos - Java Day EcuadorJava y Ciencia de Datos - Java Day Ecuador
Java y Ciencia de Datos - Java Day Ecuador
 
UCIAD overview
UCIAD overviewUCIAD overview
UCIAD overview
 
A comprehensive study of non blocking joining techniques
A comprehensive study of non blocking joining techniquesA comprehensive study of non blocking joining techniques
A comprehensive study of non blocking joining techniques
 
A comprehensive study of non blocking joining technique
A comprehensive study of non blocking joining techniqueA comprehensive study of non blocking joining technique
A comprehensive study of non blocking joining technique
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
Software Sustainability: Better Software Better Science
Software Sustainability: Better Software Better ScienceSoftware Sustainability: Better Software Better Science
Software Sustainability: Better Software Better Science
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
How Secure Are Docker Containers?
How Secure Are Docker Containers?How Secure Are Docker Containers?
How Secure Are Docker Containers?
 
Data Management for Quantitative Biology - Database Systems (continued) LIMS ...
Data Management for Quantitative Biology - Database Systems (continued) LIMS ...Data Management for Quantitative Biology - Database Systems (continued) LIMS ...
Data Management for Quantitative Biology - Database Systems (continued) LIMS ...
 
Meetup rio
Meetup rioMeetup rio
Meetup rio
 
FIWARE Wednesday Webinars - Performing Big Data Analysis Using Cosmos With Sp...
FIWARE Wednesday Webinars - Performing Big Data Analysis Using Cosmos With Sp...FIWARE Wednesday Webinars - Performing Big Data Analysis Using Cosmos With Sp...
FIWARE Wednesday Webinars - Performing Big Data Analysis Using Cosmos With Sp...
 
Struts2.x
Struts2.xStruts2.x
Struts2.x
 
Possible Worlds Explorer: Datalog & Answer Set Programming for the Rest of Us
Possible Worlds Explorer: Datalog & Answer Set Programming for the Rest of UsPossible Worlds Explorer: Datalog & Answer Set Programming for the Rest of Us
Possible Worlds Explorer: Datalog & Answer Set Programming for the Rest of Us
 
Smarter internet of things with stream and event processing virtual io_t_meet...
Smarter internet of things with stream and event processing virtual io_t_meet...Smarter internet of things with stream and event processing virtual io_t_meet...
Smarter internet of things with stream and event processing virtual io_t_meet...
 

Recently uploaded

Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPsychicRuben LoveSpells
 
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Servicenishacall1
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfCWS Technology
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRnishacall1
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceDelhi Call girls
 

Recently uploaded (6)

Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
 
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
9999266834 Call Girls In Noida Sector 52 (Delhi) Call Girl Service
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdf
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
 
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
 

Functional reactive android (with Groovy)

  • 2. Presentation Structure ● Who ● Why ● What ● How
  • 3. Who Carlos Anjos Senior Android Developer @ Muzzley, an awesome IoT Startup Handle: “${lastname}${firstname[0]}” Email: “${handle}@gmail.com” or “${firstname}.${lastname}@muzzley.com” More: “https://pt.linkedin.com/in/${handle}”
  • 5. Tech reasons Moore's law - the observation that the number of transistors in a dense integrated circuit doubles approximately every two years We’re moving to more cores ...
  • 6. Human reasons ● Working memory only holds 7 +- 2 items at the same time ● But we’re able to use Chunking “Chunking in psychology is a process by which individual pieces of information are bound together into a meaningful whole (Neath & Surprenant, 2003)”
  • 7. We need greater abstractions “The power of the unaided mind is highly overrated. Without external aids, memory, thought, and reasoning are all constrained. But human intelligence is highly flexible and adaptive, superb at inventing procedures and objects that overcome its own limits” - Donald Droman, in “Things that make us smart” Examples: Assembly -> Fortran -> C -> C++ -> Java -> Groovy -> ? Traditional IT -> Iaas -> Paas -> Saas -> XaaS (microservices like Amazon lambda, Google Cloud Functions)
  • 9.
  • 10. What is Functional f(x) = x + 2 int f(int x) { return x + 2 } ● Does not keep state ● For same input, always same output ● Everything the function needs is provided as a parameter ● Immutable: ○ Integer f(Integer x) { return new Integer(x.intValue() + 2) } ○ x.setInt(7)
  • 11. Why functional ● Parallelization ● Microservices ● Readability ● Language Agnostic
  • 12. What is Reactive Reacts to events / Hollywood pattern Iterator -> pull Observer -> push interface Iterator<T> { boolean hasNext(); T next(); } interface Observer<T> { onNext(T t); onCompleted(); onError(Throwable e); }
  • 13. Why reactive Easy Threading No callback hell Function composition A ton of operators Easier to reason about Common vocabulary across languages and platforms (java, swift, etc)
  • 14.
  • 15. Rx Example // print every item in the array [1,2,3] Observable.from(Arrays.asList(1,2,3)).subscribe(new Action1<Integer>() { @Override public void call(Integer i) { System.out.println(i); } }); // in java Observable.from(Arrays.asList(1,2,3)).subscribe((Integer i)->{ println(i) })//(Java 8) Observable.from([1,2,3]).subscribe { println(it) } //(in Groovy)
  • 16. Retrofit @PATCH("/users/{userId}") Observable<User> setUser(@Path("userId") String userId, @Body User user); api.setUser(userPreference.getId(), newUserPatch) .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe( {userPreference.save()}, {Timber.d(it,"Error sending new prefs async")} )
  • 17. RxAndroid Observable.combineLatest( ViewObservable.text(editGroupName), adapter.getCurrentSelectedChannelObservable(), { OnTextChangeEvent onTextChangeEvent, List<String> selectedChannelIds - > onTextChangeEvent.text.length() > 0 && selectedChannelIds.size() >= 2 }) .subscribe { buttonNext.setEnabled(it)}
  • 18. Tons of operators latLngObservable.debounce(500, TimeUnit.MILLISECONDS).flatMap { place.latitude = it.latitude place.longitude = it.longitude Observable.create(new GeocoderSubscriber(geocoder, it)) }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe({ place.address = it mAddress.setText(it); }, { FeedbackMessages.showMessage(mAddress,"Error getting address") });
  • 21. What is Groovy JVM language Born in 2003 Inspired by Java, Python, Ruby, Perl, Smalltalk, Objective-C “Superset” of java Apache license Dynamic by default, but also Static if you want to (and I do !)
  • 22. Why groovy Already using it for the build system (although Kotlin in the future ?) Looks like java Easier to transition to Good IDE support Much less verbose Array and map literals, closures, null safe navigation More functional Apache Project and License
  • 23. Closures, multiline string & interpolation, safe nulls new AlertDialog.Builder(context) .setMessage(Html.fromHtml(""" <small><font color='#$worker.categoryColor'> ${worker.category?.toUpperCase()} </font></small><br /><br /> <b>${worker.devicesText}</b><br /><br /> ${worker.description}<br /><br /> <font color='#99a7aa'> <i>This is an advanced automation and cannot be edited</i></font> """)) .setPositiveButton("Got it", { DialogInterface dialog, int which -> gotIt()}) .show()
  • 24. Switch and casts on steroids Closure onAction(Object action){ switch (action){ case String: return {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(action as String)))} case Closure: return action as Closure default: return {startActivity(new Intent(activity, action as Class))} } }
  • 25. Much, much more ... ● Safe null navigation, boolean cohersion: If (myObj?.myInnerCollection) { doStuff() } groups?.each { group ->areas.find { it.id == group.parent }?.children?.add(group) } ● AST Transformations == Compile time meta-programming @CompileStatic, @InheritConstructors, @EqualsHashCode, @ToString, @Immutable, and many more ● Operator overloading
  • 26. Groovy caveats Debugger looses its bearings Compiler sometimes gets confused when dealing with inner classes (in groovy) Java preprocessors might not work (YMMV), although Dagger works fine

Editor's Notes

  1. Quantum computing next ?