SlideShare a Scribd company logo
–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

Hadoop
HadoopHadoop
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
Kiyotaka Oku
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
 
Testing with Node.js
Testing with Node.jsTesting with Node.js
Testing with Node.js
Jonathan Waller
 
Hack tutorial
Hack tutorialHack tutorial
Hack tutorial
Wakana Yoshizawa
 
第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
NETWAYS
 
Correcting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesCorrecting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await Mistakes
Brandon Minnick, MBA
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
Hugo Hamon
 
Polyglot parallelism
Polyglot parallelismPolyglot parallelism
Polyglot parallelism
Phillip Toland
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
Hugo 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 customization
Bartosz Konieczny
 
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
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
markstory
 
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
Katy 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 android
Rodrigo de Souza Castro
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
markstory
 
‎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
Denis 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 Example
Nikhil 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 NodeJS
Adam L Barrett
 
The evolution of asynchronous JavaScript
The evolution of asynchronous JavaScriptThe evolution of asynchronous JavaScript
The evolution of asynchronous JavaScript
Alessandro Cinelli (cirpo)
 
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 jIntegrity
Washington Botelho
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
Yekmer 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.pdf
adinathassociates
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
Tomáš Kypta
 
Dropwizard
DropwizardDropwizard
Dropwizard
Scott Leberknight
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
Zianed Hou
 
Apache Beam de A à Z
 Apache Beam de A à Z Apache Beam de A à Z
Apache Beam de A à Z
Paris Data Engineers !
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
cbeyls
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
Gabriele Lana
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
Dan Hinojosa
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
Oleg Podsechin
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
Shaul Rosenzwieg
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
Dmytro 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
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
Bruno Scopelliti
 
Operation Flow @ ChicagoRoboto
Operation Flow @ ChicagoRobotoOperation Flow @ ChicagoRoboto
Operation Flow @ ChicagoRoboto
Seyed 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

PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
PauloRodrigues104553
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
RadiNasr
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
awadeshbabu
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
University of Maribor
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
rpskprasana
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Wearable antenna for antenna applications
Wearable antenna for antenna applicationsWearable antenna for antenna applications
Wearable antenna for antenna applications
Madhumitha Jayaram
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
ssuser36d3051
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
MIGUELANGEL966976
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
JamalHussainArman
 

Recently uploaded (20)

PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
 
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdfIron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
Iron and Steel Technology Roadmap - Towards more sustainable steelmaking.pdf
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Wearable antenna for antenna applications
Wearable antenna for antenna applicationsWearable antenna for antenna applications
Wearable antenna for antenna applications
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
 

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.