SlideShare ist ein Scribd-Unternehmen logo
1 von 54
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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!
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Kürzlich hochgeladen

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Kürzlich hochgeladen (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

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)