SlideShare a Scribd company logo
1 of 41
Download to read offline
–A wise man
“True judge of courage is when you get to stand between a
man and his food”
Speaker Bio
I work at Fueled
Psst!You can too 。◕‿◕。
Isolating Flutter into
multithreading effectively
Anvith Bhat
@anv1th
Exploring Rx Dart
Exploring Rx Dart
1. Observables can be subscribed only once.
2. onListen (doOnSubscribe) called once.
3. No Schedulers ¯_(ツ)_/¯

Android to Flutter
override fun updateUi(state: ViewState) {















}
@override
Widget build(BuildContext context) {
return Container(child: _content(context));
}


Widget _content(BuildContext context) {
























}




if (state.isOnboardingCompleted) {
showPermissionDialog()
}

progress.visibility = if(state.isLoading){
View.VISIBLE
} else {
View.GONE
}
if(data.isOnboardingCompleted){
showPermissionDialog();
}
if (data.state == LoadState.LOADING) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return _Body();
}
@override
Widget build(BuildContext context) {
return Container(child: _content(context));
}


Widget _content(BuildContext context) {
























}




if(data.isOnboardingCompleted){
showPermissionDialog();
}
@override
Widget build(BuildContext context) {
return Container(child: _content(context));
}


Widget _content(BuildContext context) {
























}




if(data.isOnboardingCompleted){
Future(()=>

showPermissionDialog());
}
Flutter Framework
Flutter Framework
• Flutter engine does not create its own threads or
manage them
Platform Task

Runner
UI Task 

Runner
IO Task 

Runner
GPU Task 

Runner
Embedder
Load Costs
Accessible Load Behaviour
Platform Task Runner Yes
Gesture events dropped 

and app termination
UI Task Runner Yes Frame dropping/jank
IO Task Runner No Delayed Futures
GPU Task Runner No Frame dropping/jank
Flutter Thread Quirks
• Threading Api is implicit.

• Futures and Async/Await solve problems of asynchrony not
computation.
Isolates
• Don't share memory.
• Data wired is copied
• Parents can limit abilities of isolates.
IsolatesAttributes
Isolates
Threads Looper
Control 

Port
Capability
SendPort ReceivePort
pause/resume/killIsolate
Anatomy
Isolate Port
spawn(port)
PortApp
send/listen
How do I make em 🤔


Future<int> startIsolate() async {














}



1. Isolate.spawn(runnable, runnable_param)
//Create a Port for communication

ReceivePort receivePort = ReceivePort();
//Create the isolate

await Isolate.spawn(computeMatrix, 

receivePort.sendPort);
//Pick first item in stream

return await receivePort.first;
//Callback
void computeMatrix(SendPort port) {
var result = heavilyComputedValue();
port.send(result)
}

void onButtonClick() {
startIsolate().then((computedValue) {

setState(() {
computedText = "Matrix result is 

${computedValue}";
});

});
}
How do I make em 🤔
void createRestrictedIsolate(Isolate main){



//Proxy
Isolate restrictedIsolate = new Isolate(main.controlPort);

untrustedCode(restrictedIsolate);
}
1. Isolate.spawn(callback, callback_param)
2. via Constructor
How do I make em 🤔
1. Isolate.spawn(callback, callback_param)
3. spawnUri(Uri uri, List<String> args)
Future<void> executeFileContent(Isolate main) async{


var args =List<String>();

args.add("type=monthly_data");

var isolate = await Isolate.spawnUri('./periodic_sync.dart',args)



}
2. via Constructor
Processing Large Data
• Flutter copies data on the parent isolate.
• TransferableTypedData creates cross isolate transferrable
buffer.









void sendData(SendPort replyPort){













}
void receiveData(ReceivePort receivePort) async {






}
dynamic x = new ByteData(2 * 1024 * 1024);
for (int i = 0; i < 4; i++) {
x.setInt8(i, i);
}
replyPort.send(TransferableTypedData.fromList([x.buffer.asUint8List()]));
var first = await receivePort.first as TransferableTypedData;
var data = first.materialize().asByteData();
Benchmarks
• Spawn time for a typical isolate varies between 10-80ms
• Each isolate is allocated an independent heap. Around 5-6 mb
on a higher end phone.
• Isolate creation times on android are almost 8-10x of ios.
Advanced Usages
• Object Registry
• Isolate Runner
• Load balancers

pub:isolate
Isolate Runner
• Allows one to check if the runner is still alive.
• Specify timeouts via. run function
Wrapper around creation of Isolates.
Future<R> run<R, P>(FutureOr<R> function(P argument), P argument,
{Duration timeout}) {
Load Balancers
• Create and Manage Isolate runner pool.

var balancer = LoadBalancer.create(POOL_SIZE, IsolateRunner.spawn)

 balancer.run(heavyCompute, heavyComputeArg, estimatedLoad)
Isolate + Streams
getMatrixObservable()
.asyncMap(startIsolate)

.listen((data){
print("Me gots data")
});
- asyncMap

Future<int> startIsolate(int a) async {
ReceivePort receivePort = ReceivePort();

Isolate isolate = await Isolate.spawn(isolateTask, receivePort.sendPort);
return await receivePort.first;
}
Isolate + Streams
- fromFuture
- asyncMap

Future<int> startIsolate() async {
ReceivePort receivePort = ReceivePort();

Isolate isolate = await Isolate.spawn(isolateTask, receivePort.sendPort);
return await receivePort.first;
}
Observable

.fromFuture(startIsolate())

.listen((data){
print("I come from the future: $data")
});;
An Idiomatic Spell
• Stream transformers operator 

could help out
Observable.just(value)
.observeOn(Schedulers.io())

class IoScheduler<S, T> implements StreamTransformer<S, T> {





















}
class IoScheduler<S, T> implements StreamTransformer<S, T> {



















































}
if (_loadBalancer == null) {
_loadBalancer = await LoadBalancer.create(POOL_SIZE, IsolateRunner.spawn);
}
// Create isolate pool

static Future<void> initLoadBalancer() async {
// Isolate pool state



static LoadBalancer _loadBalancer;

static const int POOL_SIZE = 6;
}
class IoScheduler<S, T> implements StreamTransformer<S, T> {



















































}
// Initialise stream handlers



IoScheduler(S isolateCode(T value)) {
}
_transformer = isolateCode;
_controller = new StreamController<T>(
onListen: _onListen

);
Function _transformer;
Future<void> initLoadBalancer() async {..}
class IoScheduler<S, T> implements StreamTransformer<S, T> {



















































}
// Initialise stream handlers



IoScheduler(S isolateCode(T value)) {..}
Function _transformer;
}
void _onListen() {
_subscription = _stream.listen(

onData,
onError: _controller.addError
);
Future<void> initLoadBalancer() async {..}
class IoScheduler<S, T> implements StreamTransformer<S, T> {




















































}
..}void _onListen() {
void onData(S data) {
initLoadBalancer().then((val) {











});
}
_loadBalancer.run(_transformer, data).then((transformed) {
_controller.add(transformed as T);
}, onError: (error) {
throw error;
});

// Initialise stream handlers



IoScheduler(S isolateCode(T value)) { ..}
Function _transformer;
Future<void> initLoadBalancer() async {..}
The Final Spell
Observable getFibonnaciValue(int value) {



return Observable.just(value)
.transform(IoScheduler<int, int>(calculateFib));

}
int calculateFib(int n) {
if (n <= 1)
return n;
else
return calculateFib(n - 1) + calculateFib(n - 2);
}
The "not so good" parts
• Copy overheads*
• Isolate creation times are sporadic.
• Doesn't guarantee true parallelism all the time. Since they're
backed byVM thread pool.
Takeaways
• Avoid isolates for simpler tasks like object transformations.
• Use Isolates for json decoding, encryption and image processing.
• Figure out a pool size that works well for your app. Around 5-6
isolates are good enough for most apps.
• Profile your app.
Resources
• IoScheduler/IoTransformer

https://gist.github.com/humblerookie/9b395f653a81cca17280921175064232
• Isolates Playground

https://github.com/humblerookie/isolates-playground/
Questions?
Thanks.
Anvith Bhat
@anv1th

More Related Content

What's hot

JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data ObjectsWez Furlong
 
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)潤一 加藤
 
Zabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensZabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensNETWAYS
 
Correcting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesCorrecting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesBrandon Minnick, MBA
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationBartosz Konieczny
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3markstory
 
How to use redux with react hooks in react native application
How to use redux with react hooks in react native applicationHow to use redux with react hooks in react native application
How to use redux with react hooks in react native applicationKaty Slemon
 
A evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidA evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidRodrigo de Souza Castro
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHPmarkstory
 
‎Unit tests automation for legacy code‎ at YAPC::NA 2016
‎Unit tests automation for legacy code‎ at YAPC::NA 2016‎Unit tests automation for legacy code‎ at YAPC::NA 2016
‎Unit tests automation for legacy code‎ at YAPC::NA 2016Denis Shirokov
 
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code ExampleMaven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code ExampleNikhil Bhalwankar
 
Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]Devon Bernard
 

What's hot (20)

Hadoop
HadoopHadoop
Hadoop
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Testing with Node.js
Testing with Node.jsTesting with Node.js
Testing with Node.js
 
Hack tutorial
Hack tutorialHack tutorial
Hack tutorial
 
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
 
Zabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensZabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet Mens
 
Correcting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesCorrecting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await Mistakes
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
Polyglot parallelism
Polyglot parallelismPolyglot parallelism
Polyglot parallelism
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customization
 
The zen of async: Best practices for best performance
The zen of async: Best practices for best performanceThe zen of async: Best practices for best performance
The zen of async: Best practices for best performance
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
How to use redux with react hooks in react native application
How to use redux with react hooks in react native applicationHow to use redux with react hooks in react native application
How to use redux with react hooks in react native application
 
A evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidA evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no android
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
 
‎Unit tests automation for legacy code‎ at YAPC::NA 2016
‎Unit tests automation for legacy code‎ at YAPC::NA 2016‎Unit tests automation for legacy code‎ at YAPC::NA 2016
‎Unit tests automation for legacy code‎ at YAPC::NA 2016
 
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code ExampleMaven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
 
Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]Lean React - Patterns for High Performance [ploneconf2017]
Lean React - Patterns for High Performance [ploneconf2017]
 

Similar to Droidjam 2019 flutter isolates pdf

Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Paco de la Cruz
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityWashington Botelho
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
Java Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfJava Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfadinathassociates
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Zianed Hou
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloadedcbeyls
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewDmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.UA Mobile
 
Operation Flow @ ChicagoRoboto
Operation Flow @ ChicagoRobotoOperation Flow @ ChicagoRoboto
Operation Flow @ ChicagoRobotoSeyed Jafari
 

Similar to Droidjam 2019 flutter isolates pdf (20)

Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
The evolution of asynchronous JavaScript
The evolution of asynchronous JavaScriptThe evolution of asynchronous JavaScript
The evolution of asynchronous JavaScript
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Java Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfJava Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdf
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
Apache Beam de A à Z
 Apache Beam de A à Z Apache Beam de A à Z
Apache Beam de A à Z
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Operation Flow @ ChicagoRoboto
Operation Flow @ ChicagoRobotoOperation Flow @ ChicagoRoboto
Operation Flow @ ChicagoRoboto
 

Recently uploaded

VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 

Recently uploaded (20)

VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 

Droidjam 2019 flutter isolates pdf

  • 1. –A wise man “True judge of courage is when you get to stand between a man and his food”
  • 2. Speaker Bio I work at Fueled Psst!You can too 。◕‿◕。
  • 3. Isolating Flutter into multithreading effectively Anvith Bhat @anv1th
  • 5. Exploring Rx Dart 1. Observables can be subscribed only once. 2. onListen (doOnSubscribe) called once. 3. No Schedulers ¯_(ツ)_/¯

  • 6. Android to Flutter override fun updateUi(state: ViewState) {
 
 
 
 
 
 
 
 } @override Widget build(BuildContext context) { return Container(child: _content(context)); } 
 Widget _content(BuildContext context) { 
 
 
 
 
 
 
 
 
 
 
 
 } 
 
 if (state.isOnboardingCompleted) { showPermissionDialog() }
 progress.visibility = if(state.isLoading){ View.VISIBLE } else { View.GONE } if(data.isOnboardingCompleted){ showPermissionDialog(); } if (data.state == LoadState.LOADING) { return Center( child: CircularProgressIndicator(), ); } else { return _Body(); }
  • 7.
  • 8. @override Widget build(BuildContext context) { return Container(child: _content(context)); } 
 Widget _content(BuildContext context) { 
 
 
 
 
 
 
 
 
 
 
 
 } 
 
 if(data.isOnboardingCompleted){ showPermissionDialog(); } @override Widget build(BuildContext context) { return Container(child: _content(context)); } 
 Widget _content(BuildContext context) { 
 
 
 
 
 
 
 
 
 
 
 
 } 
 
 if(data.isOnboardingCompleted){ Future(()=>
 showPermissionDialog()); }
  • 9.
  • 11. Flutter Framework • Flutter engine does not create its own threads or manage them Platform Task
 Runner UI Task 
 Runner IO Task 
 Runner GPU Task 
 Runner Embedder
  • 12. Load Costs Accessible Load Behaviour Platform Task Runner Yes Gesture events dropped 
 and app termination UI Task Runner Yes Frame dropping/jank IO Task Runner No Delayed Futures GPU Task Runner No Frame dropping/jank
  • 13. Flutter Thread Quirks • Threading Api is implicit.
 • Futures and Async/Await solve problems of asynchrony not computation.
  • 15. • Don't share memory. • Data wired is copied • Parents can limit abilities of isolates. IsolatesAttributes
  • 19. How do I make em 🤔 
 Future<int> startIsolate() async { 
 
 
 
 
 
 
 }
 
 1. Isolate.spawn(runnable, runnable_param) //Create a Port for communication
 ReceivePort receivePort = ReceivePort(); //Create the isolate
 await Isolate.spawn(computeMatrix, 
 receivePort.sendPort); //Pick first item in stream
 return await receivePort.first; //Callback void computeMatrix(SendPort port) { var result = heavilyComputedValue(); port.send(result) }
 void onButtonClick() { startIsolate().then((computedValue) {
 setState(() { computedText = "Matrix result is 
 ${computedValue}"; });
 }); }
  • 20. How do I make em 🤔 void createRestrictedIsolate(Isolate main){
 
 //Proxy Isolate restrictedIsolate = new Isolate(main.controlPort);
 untrustedCode(restrictedIsolate); } 1. Isolate.spawn(callback, callback_param) 2. via Constructor
  • 21. How do I make em 🤔 1. Isolate.spawn(callback, callback_param) 3. spawnUri(Uri uri, List<String> args) Future<void> executeFileContent(Isolate main) async{ 
 var args =List<String>();
 args.add("type=monthly_data");
 var isolate = await Isolate.spawnUri('./periodic_sync.dart',args)
 
 } 2. via Constructor
  • 22. Processing Large Data • Flutter copies data on the parent isolate. • TransferableTypedData creates cross isolate transferrable buffer.
 
 
 
 

  • 23. void sendData(SendPort replyPort){
 
 
 
 
 
 
 } void receiveData(ReceivePort receivePort) async { 
 
 
 } dynamic x = new ByteData(2 * 1024 * 1024); for (int i = 0; i < 4; i++) { x.setInt8(i, i); } replyPort.send(TransferableTypedData.fromList([x.buffer.asUint8List()])); var first = await receivePort.first as TransferableTypedData; var data = first.materialize().asByteData();
  • 24. Benchmarks • Spawn time for a typical isolate varies between 10-80ms • Each isolate is allocated an independent heap. Around 5-6 mb on a higher end phone. • Isolate creation times on android are almost 8-10x of ios.
  • 25.
  • 26. Advanced Usages • Object Registry • Isolate Runner • Load balancers
 pub:isolate
  • 27. Isolate Runner • Allows one to check if the runner is still alive. • Specify timeouts via. run function Wrapper around creation of Isolates. Future<R> run<R, P>(FutureOr<R> function(P argument), P argument, {Duration timeout}) {
  • 28. Load Balancers • Create and Manage Isolate runner pool.
 var balancer = LoadBalancer.create(POOL_SIZE, IsolateRunner.spawn) 
 balancer.run(heavyCompute, heavyComputeArg, estimatedLoad)
  • 29. Isolate + Streams getMatrixObservable() .asyncMap(startIsolate)
 .listen((data){ print("Me gots data") }); - asyncMap
 Future<int> startIsolate(int a) async { ReceivePort receivePort = ReceivePort();
 Isolate isolate = await Isolate.spawn(isolateTask, receivePort.sendPort); return await receivePort.first; }
  • 30. Isolate + Streams - fromFuture - asyncMap
 Future<int> startIsolate() async { ReceivePort receivePort = ReceivePort();
 Isolate isolate = await Isolate.spawn(isolateTask, receivePort.sendPort); return await receivePort.first; } Observable
 .fromFuture(startIsolate())
 .listen((data){ print("I come from the future: $data") });;
  • 31. An Idiomatic Spell • Stream transformers operator 
 could help out Observable.just(value) .observeOn(Schedulers.io())

  • 32. class IoScheduler<S, T> implements StreamTransformer<S, T> {
 
 
 
 
 
 
 
 
 
 
 }
  • 33. class IoScheduler<S, T> implements StreamTransformer<S, T> {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 } if (_loadBalancer == null) { _loadBalancer = await LoadBalancer.create(POOL_SIZE, IsolateRunner.spawn); } // Create isolate pool
 static Future<void> initLoadBalancer() async { // Isolate pool state
 
 static LoadBalancer _loadBalancer;
 static const int POOL_SIZE = 6; }
  • 34. class IoScheduler<S, T> implements StreamTransformer<S, T> {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 } // Initialise stream handlers
 
 IoScheduler(S isolateCode(T value)) { } _transformer = isolateCode; _controller = new StreamController<T>( onListen: _onListen
 ); Function _transformer; Future<void> initLoadBalancer() async {..}
  • 35. class IoScheduler<S, T> implements StreamTransformer<S, T> {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 } // Initialise stream handlers
 
 IoScheduler(S isolateCode(T value)) {..} Function _transformer; } void _onListen() { _subscription = _stream.listen(
 onData, onError: _controller.addError ); Future<void> initLoadBalancer() async {..}
  • 36. class IoScheduler<S, T> implements StreamTransformer<S, T> { 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 } ..}void _onListen() { void onData(S data) { initLoadBalancer().then((val) {
 
 
 
 
 
 }); } _loadBalancer.run(_transformer, data).then((transformed) { _controller.add(transformed as T); }, onError: (error) { throw error; });
 // Initialise stream handlers
 
 IoScheduler(S isolateCode(T value)) { ..} Function _transformer; Future<void> initLoadBalancer() async {..}
  • 37. The Final Spell Observable getFibonnaciValue(int value) {
 
 return Observable.just(value) .transform(IoScheduler<int, int>(calculateFib));
 } int calculateFib(int n) { if (n <= 1) return n; else return calculateFib(n - 1) + calculateFib(n - 2); }
  • 38. The "not so good" parts • Copy overheads* • Isolate creation times are sporadic. • Doesn't guarantee true parallelism all the time. Since they're backed byVM thread pool.
  • 39. Takeaways • Avoid isolates for simpler tasks like object transformations. • Use Isolates for json decoding, encryption and image processing. • Figure out a pool size that works well for your app. Around 5-6 isolates are good enough for most apps. • Profile your app.