SlideShare uma empresa Scribd logo
1 de 54
Baixar para ler offline
Deep dive
into Android async operations
Mateusz Grzechociński
@mgrzechocinski
Demo app source code
https://github.com/mgrzechocinski/DroidconKrakow2014
What’s it for?
● Confitura 2010
● Review & share own experience
● ...and would appreciate your’s
● From developer to (intermediate) developers
Meet Adam
...and his story
Adam, a developer who knows
● what’s Looper.loop()
● what ANR is
● Long operation? Spawn a thread!
Requirements
● Bundesliga matches results
● Refresh on click
Simple enough?
● REST client
● 1 activity
● 1 button,
● refresh = call URLs in spawned threads
StrictMode
public class DemoApp extends Application {
@Override
public void onCreate() {
super.onCreate();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
}
}
"AsyncTask enables proper and easy use of
the UI thread. This class allows to perform
background operations and publish results on
the UI thread without having to manipulate
threads and/or handlers.”
Android SDK docs
Performing network operations
DEMO 1
AsyncTask - multiple calls
< DONUT DONUT >=HONEYCOMB
SERIAL PARALLEL SERIAL
AsyncTask.executeOnExecutor(Executor)
DEMO 1a
AsyncTask - memory leak
Solutions
● Track activity/fragment lifecycle manually
○ cancel it?
● Use fragment with setRetainInstance
(true)
AsyncTask
Pros
● Simple
● Great for few seconds
operations
● Cancellation support
Cons
● Memory leaks,
● Possible crashes
● Behaves different
● Lack of exceptions handling
(or RoboAsyncTask)
http://stackoverflow.com/questions/3357477/is-asynctask-really-conceptually-flawed-or-am-i-just-
missing-something
Adam wonders: Really a good idea?
run task
→ change config (e.g. by rotating the screen)
→ cancel previous task
→ run new task
→ update UI
Loaders
● HONEYCOMB+
● support-v4
Loaders, in particular CursorLoader, are
expected to retain their data after being
stopped. This allows applications to keep
their data across the activity or fragment's
onStop() and onStart() methods, so that when
users return to an application, they don't
have to wait for the data to reload.
Android SDK docs
AsyncTaskLoader
“This class performs the same function as
the AsyncTask, but a bit better. It can
handle Activity configuration changes more
easily (add MG: by Loader Manager), and it
behaves within the life cycles of Fragments
and Activities.”
http://www.javacodegeeks.com/2013/01/android-loaders-versus-asynctask.html
How it works...
● LoaderManager
● initLoader
● LoaderCallback
● CursorLoader
● AsyncTaskLoader
DEMO 2
Loader - first shoot and…
nothing
WHY?
@Override
protected void onStartLoading() {
super.onStartLoading();
Log.d(LOG_TAG, "onStartLoading");
+ forceLoad();
}
DEMO 3
Loader - forceLoad()
config change?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matches);
if (savedInstanceState != null) {
+ getSupportLoaderManager().initLoader(LOADER_ID, args, this);
//restore state...
}
}
DEMO 4
Loader - config change
leaving activity?
@Override
protected void onStartLoading() {
super.onStartLoading();
Log.d(LOG_TAG, "onStartLoading");
+ if(result == null){
forceLoad();
+ }else{
+ deliverResult(result);
+ }
}
DEMO 5
Loader - leaving activity (home etc)
force refresh?
@Override
public void onLoadFinished(Loader<Match> loader, Match match) {
Log.d(LOG_TAG, "onLoadFinished: " + match);
currentMatches.add(match);
adapter.setCurrentMatches(currentMatches);
adapter.notifyDataSetChanged();
+ getSupportLoaderManager().destroyLoader(LOADER_ID);
}
DEMO 6
Loader - force refresh
Loader
Pros
● Better than AsyncTask, much
● Gives “partial” caching
○ Need in-loader result
caching when leaving
activity
○ No control
● No memory leaks
Cons
● Designed to support DB data
(cursor)
● Hacking, hacking, hacking to
use in networking
● Poorly documented
● Opposite to AsyncTask
○ too highly coupled
● Poor exception management
https://github.com/stephanenicolas/robospice/wiki/A-User's-Perspective-on-RoboSpice
The idea
“[...]
Basically, what happens with RS is that when a request is being
processed, its listeners will be invoked as long as the associated
activity is alive.
[...]
The main purpose of RS is to make sure that there is no memory leak :
your activity, if it has to die, will die and be garbage collected, RS
doesn't hold any hard reference to it that would prevent garbage
collection. That's really the core idea behind RoboSpice. [...]”
Stephen Nicolas
http://stackoverflow.com/questions/19011200/how-does-robospice-manage-activity-lifecycle
https://www.youtube.com/watch?v=xHXn3Kg2IQE
Show me do code!
DEMO 7
RoboSpice - basic
● config change
● refresh() → no caching
@Override
protected void onStart() {
super.onStart();
spiceManager.start(this);
+ spiceManager.addListenerIfPending(Match.class, CACHE_KEY, this);
}
Config change
Force refresh
private void loadMatchesOnClick() {
int matchID = 1;
MatchResultRequest request = new MatchResultRequest(Match.class, matchID);
spiceManager.execute(request, CACHE_KEY, DurationInMillis.ALWAYS_EXPIRED, this);
}
or
spiceManager.removeDataFromCache(Match.class, CACHE_KEY);
DEMO 8
RoboSpice - extended
By default
● Handling config changes
● Full control caching
● Multithreading
● No internet connection → NoNetworkException.class
● Modules to SpringAndroid, Retrofit
● and much more...
RoboSpice
Pros
● Robust, full featured
● Last commit < 3 months ago
Cons
● POJO per Request
● No a simple library
○ SpiceManager with 1300
LOC
Go Reactive
● ReactiveExtentions by MS
● Ported by Netflix
● rxAndroid = rxJava + few Android classes
● rxJava hit 1.0
● rxAndroid still 0.x
https://github.com/ReactiveX/RxJava/wiki
Motivations
"[...] If a calling Activity/Fragment makes multiple
requests, it needs to handle responses in a single function
by switching on the URL. This makes for code that isn’t very
readable, especially when you have to jump from where the
request is executed to where the response is handled"
http://markhudnall.com/2013/10/15/rxjava-and-android/
Motivations
“It’s still a little verbose, but it’s more
similar to writing synchronous code. I use
the response in code that directly follows
the request. I also get error handling on
the UI thread for free.”
http://markhudnall.com/2013/10/15/rxjava-and-android/
Iterable Observable
getDataFromLocalMemory()
.skip(10)
.take(5)
.map({ s -> return s + " transformed" })
.forEach({ println "next => " + it })
getDataFromNetwork()
.skip(10)
.take(5)
.map({ s -> return s + " transformed" })
.subscribe({ println "onNext => " + it })
getDataFromNetwork()
.skip(10)
.take(5)
.map({ s -> return s + " transformed" })
.subscribe({ println "onNext => " + it })
DEMO 9
RxAndroid in UI Layer
Worth trying?
● Streams of events
○ e.g. Weather station, tweets analyzer
● In “common” app?
● When using Retrofit
@GET("/user/{id}/photo")
Observable<Photo> getUserPhoto(@Path("id") int id);
rxAndroid
Pros
● Reduced callback hell with
FPP
● Robust set of
functions/transformations
Cons
● Need to change the way of
thinking
● Hard, really
● On Android - even harder
● Possible memory leaks?
● Debugging?
Out of scope… or time
● IntentService (!= Service)
● Event buses (Otto, GreenRobot’s EventBus)
○ especially with Loaders
● Volley
● Ion
Remember
● Don’t use AsyncTask
● Consider using Loaders
● Give a try RoboSpice
● Learn FRP (rxJava/rxAndroid)
Thanks
Mateusz Grzechociński
@mgrzechocinski
http://grzechocinski.net

Mais conteúdo relacionado

Mais procurados

Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Fabio Collini
 
Android MvRx Framework 介紹
Android MvRx Framework 介紹Android MvRx Framework 介紹
Android MvRx Framework 介紹Kros Huang
 
Android architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaAndroid architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaPratama Nur Wijaya
 
GWT is Smarter Than You
GWT is Smarter Than YouGWT is Smarter Than You
GWT is Smarter Than YouRobert Cooper
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application ArchitectureMark Trostler
 
Testing in android
Testing in androidTesting in android
Testing in androidjtrindade
 
When Enterprise Java Micro Profile meets Angular
When Enterprise Java Micro Profile meets AngularWhen Enterprise Java Micro Profile meets Angular
When Enterprise Java Micro Profile meets AngularAntonio Goncalves
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limitsDroidcon Berlin
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupDavid Barreto
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
基於 Flow & Path 的 MVP 架構
基於 Flow & Path 的 MVP 架構基於 Flow & Path 的 MVP 架構
基於 Flow & Path 的 MVP 架構玄武 Wu
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread managementxuehan zhu
 
Android Building, Testing and reversing
Android Building, Testing and reversingAndroid Building, Testing and reversing
Android Building, Testing and reversingEnrique López Mañas
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized projectFabio Collini
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015Ben Lesh
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Roberto Franchini
 

Mais procurados (20)

Angular2
Angular2Angular2
Angular2
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2
 
Android MvRx Framework 介紹
Android MvRx Framework 介紹Android MvRx Framework 介紹
Android MvRx Framework 介紹
 
Android architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaAndroid architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta Indonesia
 
GWT is Smarter Than You
GWT is Smarter Than YouGWT is Smarter Than You
GWT is Smarter Than You
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application Architecture
 
Rx java in action
Rx java in actionRx java in action
Rx java in action
 
Testing in android
Testing in androidTesting in android
Testing in android
 
When Enterprise Java Micro Profile meets Angular
When Enterprise Java Micro Profile meets AngularWhen Enterprise Java Micro Profile meets Angular
When Enterprise Java Micro Profile meets Angular
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
 
React hooks
React hooksReact hooks
React hooks
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
基於 Flow & Path 的 MVP 架構
基於 Flow & Path 的 MVP 架構基於 Flow & Path 的 MVP 架構
基於 Flow & Path 的 MVP 架構
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Android Building, Testing and reversing
Android Building, Testing and reversingAndroid Building, Testing and reversing
Android Building, Testing and reversing
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
React Hooks
React HooksReact Hooks
React Hooks
 
RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015RxJS and Reactive Programming - Modern Web UI - May 2015
RxJS and Reactive Programming - Modern Web UI - May 2015
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 

Semelhante a Deep dive into Android async operations

Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.
Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.
Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.UA Mobile
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]GDSC UofT Mississauga
 
JSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendJSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendVlad Fedosov
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsMatteo Manchi
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang YoonJesang Yoon
 
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
"Node.js vs workers — A comparison of two JavaScript runtimes", James M SnellFwdays
 
Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"Fwdays
 
GraalVM and MicroProfile - A Polyglot Microservices Solution
GraalVM and MicroProfile - A Polyglot Microservices SolutionGraalVM and MicroProfile - A Polyglot Microservices Solution
GraalVM and MicroProfile - A Polyglot Microservices SolutionRoberto Cortez
 
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JSFestUA
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...Alessandro Molina
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
2018 (codeone) Graal VM and MicroProfile a polyglot microservices solution [d...
2018 (codeone) Graal VM and MicroProfile a polyglot microservices solution [d...2018 (codeone) Graal VM and MicroProfile a polyglot microservices solution [d...
2018 (codeone) Graal VM and MicroProfile a polyglot microservices solution [d...César Hernández
 
Introduction to Functional Reactive Web with Clojurescript
Introduction to Functional Reactive Web with ClojurescriptIntroduction to Functional Reactive Web with Clojurescript
Introduction to Functional Reactive Web with ClojurescriptJohn Stevenson
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsSrikanth Shenoy
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Enginecatherinewall
 
Intro to Flutter
Intro to FlutterIntro to Flutter
Intro to FlutterEason Pai
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersJavan Rasokat
 
Docker and Your Path to a Better Staging Environment - webinar by Gil Tayar
Docker and Your Path to a Better Staging Environment - webinar by Gil TayarDocker and Your Path to a Better Staging Environment - webinar by Gil Tayar
Docker and Your Path to a Better Staging Environment - webinar by Gil TayarApplitools
 

Semelhante a Deep dive into Android async operations (20)

Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.
Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.
Критика "библиотечного" подхода в разработке под Android. UA Mobile 2016.
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
JSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendJSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontend
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
Advanced android app development
Advanced android app developmentAdvanced android app development
Advanced android app development
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoon
 
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
"Node.js vs workers — A comparison of two JavaScript runtimes", James M Snell
 
Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"
 
GraalVM and MicroProfile - A Polyglot Microservices Solution
GraalVM and MicroProfile - A Polyglot Microservices SolutionGraalVM and MicroProfile - A Polyglot Microservices Solution
GraalVM and MicroProfile - A Polyglot Microservices Solution
 
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
2018 (codeone) Graal VM and MicroProfile a polyglot microservices solution [d...
2018 (codeone) Graal VM and MicroProfile a polyglot microservices solution [d...2018 (codeone) Graal VM and MicroProfile a polyglot microservices solution [d...
2018 (codeone) Graal VM and MicroProfile a polyglot microservices solution [d...
 
Introduction to Functional Reactive Web with Clojurescript
Introduction to Functional Reactive Web with ClojurescriptIntroduction to Functional Reactive Web with Clojurescript
Introduction to Functional Reactive Web with Clojurescript
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
 
Intro to Flutter
Intro to FlutterIntro to Flutter
Intro to Flutter
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA Testers
 
Docker and Your Path to a Better Staging Environment - webinar by Gil Tayar
Docker and Your Path to a Better Staging Environment - webinar by Gil TayarDocker and Your Path to a Better Staging Environment - webinar by Gil Tayar
Docker and Your Path to a Better Staging Environment - webinar by Gil Tayar
 
Node.js Course 2 of 2 - Advanced techniques
Node.js Course 2 of 2 - Advanced techniquesNode.js Course 2 of 2 - Advanced techniques
Node.js Course 2 of 2 - Advanced techniques
 

Mais de Mateusz Grzechociński (7)

Save users' data!
Save users' data!Save users' data!
Save users' data!
 
Meet Jack & Jill
Meet Jack & JillMeet Jack & Jill
Meet Jack & Jill
 
Gitkata push and_pull_options
Gitkata push and_pull_optionsGitkata push and_pull_options
Gitkata push and_pull_options
 
Gitkata refspec
Gitkata refspecGitkata refspec
Gitkata refspec
 
Gitkata fish shell
Gitkata fish shellGitkata fish shell
Gitkata fish shell
 
Gitkata undoing changes
Gitkata undoing changesGitkata undoing changes
Gitkata undoing changes
 
Gitkata rerere
Gitkata rerereGitkata rerere
Gitkata rerere
 

Último

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Deep dive into Android async operations

  • 1. Deep dive into Android async operations Mateusz Grzechociński @mgrzechocinski Demo app source code https://github.com/mgrzechocinski/DroidconKrakow2014
  • 2. What’s it for? ● Confitura 2010 ● Review & share own experience ● ...and would appreciate your’s ● From developer to (intermediate) developers
  • 5. Adam, a developer who knows ● what’s Looper.loop() ● what ANR is ● Long operation? Spawn a thread!
  • 6. Requirements ● Bundesliga matches results ● Refresh on click
  • 7. Simple enough? ● REST client ● 1 activity ● 1 button, ● refresh = call URLs in spawned threads
  • 8. StrictMode public class DemoApp extends Application { @Override public void onCreate() { super.onCreate(); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build()); } }
  • 9. "AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.” Android SDK docs
  • 11. DEMO 1 AsyncTask - multiple calls
  • 12. < DONUT DONUT >=HONEYCOMB SERIAL PARALLEL SERIAL AsyncTask.executeOnExecutor(Executor)
  • 13. DEMO 1a AsyncTask - memory leak
  • 14.
  • 15. Solutions ● Track activity/fragment lifecycle manually ○ cancel it? ● Use fragment with setRetainInstance (true)
  • 16. AsyncTask Pros ● Simple ● Great for few seconds operations ● Cancellation support Cons ● Memory leaks, ● Possible crashes ● Behaves different ● Lack of exceptions handling (or RoboAsyncTask) http://stackoverflow.com/questions/3357477/is-asynctask-really-conceptually-flawed-or-am-i-just- missing-something
  • 17. Adam wonders: Really a good idea? run task → change config (e.g. by rotating the screen) → cancel previous task → run new task → update UI
  • 19. Loaders, in particular CursorLoader, are expected to retain their data after being stopped. This allows applications to keep their data across the activity or fragment's onStop() and onStart() methods, so that when users return to an application, they don't have to wait for the data to reload. Android SDK docs
  • 20. AsyncTaskLoader “This class performs the same function as the AsyncTask, but a bit better. It can handle Activity configuration changes more easily (add MG: by Loader Manager), and it behaves within the life cycles of Fragments and Activities.” http://www.javacodegeeks.com/2013/01/android-loaders-versus-asynctask.html
  • 21. How it works... ● LoaderManager ● initLoader ● LoaderCallback ● CursorLoader ● AsyncTaskLoader
  • 22. DEMO 2 Loader - first shoot and… nothing WHY?
  • 23.
  • 24. @Override protected void onStartLoading() { super.onStartLoading(); Log.d(LOG_TAG, "onStartLoading"); + forceLoad(); }
  • 25. DEMO 3 Loader - forceLoad() config change?
  • 26. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_matches); if (savedInstanceState != null) { + getSupportLoaderManager().initLoader(LOADER_ID, args, this); //restore state... } }
  • 27. DEMO 4 Loader - config change leaving activity?
  • 28. @Override protected void onStartLoading() { super.onStartLoading(); Log.d(LOG_TAG, "onStartLoading"); + if(result == null){ forceLoad(); + }else{ + deliverResult(result); + } }
  • 29. DEMO 5 Loader - leaving activity (home etc) force refresh?
  • 30. @Override public void onLoadFinished(Loader<Match> loader, Match match) { Log.d(LOG_TAG, "onLoadFinished: " + match); currentMatches.add(match); adapter.setCurrentMatches(currentMatches); adapter.notifyDataSetChanged(); + getSupportLoaderManager().destroyLoader(LOADER_ID); }
  • 31. DEMO 6 Loader - force refresh
  • 32. Loader Pros ● Better than AsyncTask, much ● Gives “partial” caching ○ Need in-loader result caching when leaving activity ○ No control ● No memory leaks Cons ● Designed to support DB data (cursor) ● Hacking, hacking, hacking to use in networking ● Poorly documented ● Opposite to AsyncTask ○ too highly coupled ● Poor exception management
  • 34. The idea “[...] Basically, what happens with RS is that when a request is being processed, its listeners will be invoked as long as the associated activity is alive. [...] The main purpose of RS is to make sure that there is no memory leak : your activity, if it has to die, will die and be garbage collected, RS doesn't hold any hard reference to it that would prevent garbage collection. That's really the core idea behind RoboSpice. [...]” Stephen Nicolas http://stackoverflow.com/questions/19011200/how-does-robospice-manage-activity-lifecycle
  • 36. Show me do code!
  • 37. DEMO 7 RoboSpice - basic ● config change ● refresh() → no caching
  • 38. @Override protected void onStart() { super.onStart(); spiceManager.start(this); + spiceManager.addListenerIfPending(Match.class, CACHE_KEY, this); } Config change
  • 39. Force refresh private void loadMatchesOnClick() { int matchID = 1; MatchResultRequest request = new MatchResultRequest(Match.class, matchID); spiceManager.execute(request, CACHE_KEY, DurationInMillis.ALWAYS_EXPIRED, this); } or spiceManager.removeDataFromCache(Match.class, CACHE_KEY);
  • 40. DEMO 8 RoboSpice - extended
  • 41. By default ● Handling config changes ● Full control caching ● Multithreading ● No internet connection → NoNetworkException.class ● Modules to SpringAndroid, Retrofit ● and much more...
  • 42. RoboSpice Pros ● Robust, full featured ● Last commit < 3 months ago Cons ● POJO per Request ● No a simple library ○ SpiceManager with 1300 LOC
  • 43. Go Reactive ● ReactiveExtentions by MS ● Ported by Netflix ● rxAndroid = rxJava + few Android classes ● rxJava hit 1.0 ● rxAndroid still 0.x
  • 45. Motivations "[...] If a calling Activity/Fragment makes multiple requests, it needs to handle responses in a single function by switching on the URL. This makes for code that isn’t very readable, especially when you have to jump from where the request is executed to where the response is handled" http://markhudnall.com/2013/10/15/rxjava-and-android/
  • 46. Motivations “It’s still a little verbose, but it’s more similar to writing synchronous code. I use the response in code that directly follows the request. I also get error handling on the UI thread for free.” http://markhudnall.com/2013/10/15/rxjava-and-android/
  • 47. Iterable Observable getDataFromLocalMemory() .skip(10) .take(5) .map({ s -> return s + " transformed" }) .forEach({ println "next => " + it }) getDataFromNetwork() .skip(10) .take(5) .map({ s -> return s + " transformed" }) .subscribe({ println "onNext => " + it })
  • 48. getDataFromNetwork() .skip(10) .take(5) .map({ s -> return s + " transformed" }) .subscribe({ println "onNext => " + it })
  • 50. Worth trying? ● Streams of events ○ e.g. Weather station, tweets analyzer ● In “common” app? ● When using Retrofit @GET("/user/{id}/photo") Observable<Photo> getUserPhoto(@Path("id") int id);
  • 51. rxAndroid Pros ● Reduced callback hell with FPP ● Robust set of functions/transformations Cons ● Need to change the way of thinking ● Hard, really ● On Android - even harder ● Possible memory leaks? ● Debugging?
  • 52. Out of scope… or time ● IntentService (!= Service) ● Event buses (Otto, GreenRobot’s EventBus) ○ especially with Loaders ● Volley ● Ion
  • 53. Remember ● Don’t use AsyncTask ● Consider using Loaders ● Give a try RoboSpice ● Learn FRP (rxJava/rxAndroid)