–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();
}
Droidjam 2019 flutter isolates pdf
@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());
}
Droidjam 2019 flutter isolates pdf
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.
Droidjam 2019 flutter isolates pdf
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

PDF
What's new in jQuery 1.5
PPTX
What is row level isolation on cassandra
PPTX
Correcting Common Async/Await Mistakes in .NET
KEY
Php 101: PDO
PDF
Cassandra v3.0 at Rakuten meet-up on 12/2/2015
PDF
Road to react hooks
PPTX
Nantes Jug - Java 7
PDF
Compose Async with RxJS
What's new in jQuery 1.5
What is row level isolation on cassandra
Correcting Common Async/Await Mistakes in .NET
Php 101: PDO
Cassandra v3.0 at Rakuten meet-up on 12/2/2015
Road to react hooks
Nantes Jug - Java 7
Compose Async with RxJS

What's hot (20)

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

Similar to Droidjam 2019 flutter isolates pdf (20)

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

Recently uploaded (20)

PPTX
Principal presentation for NAAC (1).pptx
PDF
Principles of operation, construction, theory, advantages and disadvantages, ...
PDF
VSL-Strand-Post-tensioning-Systems-Technical-Catalogue_2019-01.pdf
PDF
Beginners-Guide-to-Artificial-Intelligence.pdf
PDF
MACCAFERRY GUIA GAVIONES TERRAPLENES EN ESPAÑOL
PDF
Computer organization and architecuture Digital Notes....pdf
PDF
Unit1 - AIML Chapter 1 concept and ethics
PDF
UEFA_Carbon_Footprint_Calculator_Methology_2.0.pdf
PDF
August -2025_Top10 Read_Articles_ijait.pdf
PPTX
BBOC407 BIOLOGY FOR ENGINEERS (CS) - MODULE 1 PART 1.pptx
PDF
LOW POWER CLASS AB SI POWER AMPLIFIER FOR WIRELESS MEDICAL SENSOR NETWORK
PDF
Micro 4 New.ppt.pdf a servay of cells and microorganism
PDF
Present and Future of Systems Engineering: Air Combat Systems
PDF
electrical machines course file-anna university
PDF
Computer System Architecture 3rd Edition-M Morris Mano.pdf
PDF
Project_Mgmt_Institute_-Marc Marc Marc .pdf
PPTX
Environmental studies, Moudle 3-Environmental Pollution.pptx
PDF
VTU IOT LAB MANUAL (BCS701) Computer science and Engineering
PPTX
Solar energy pdf of gitam songa hemant k
PDF
Lesson 3 .pdf
Principal presentation for NAAC (1).pptx
Principles of operation, construction, theory, advantages and disadvantages, ...
VSL-Strand-Post-tensioning-Systems-Technical-Catalogue_2019-01.pdf
Beginners-Guide-to-Artificial-Intelligence.pdf
MACCAFERRY GUIA GAVIONES TERRAPLENES EN ESPAÑOL
Computer organization and architecuture Digital Notes....pdf
Unit1 - AIML Chapter 1 concept and ethics
UEFA_Carbon_Footprint_Calculator_Methology_2.0.pdf
August -2025_Top10 Read_Articles_ijait.pdf
BBOC407 BIOLOGY FOR ENGINEERS (CS) - MODULE 1 PART 1.pptx
LOW POWER CLASS AB SI POWER AMPLIFIER FOR WIRELESS MEDICAL SENSOR NETWORK
Micro 4 New.ppt.pdf a servay of cells and microorganism
Present and Future of Systems Engineering: Air Combat Systems
electrical machines course file-anna university
Computer System Architecture 3rd Edition-M Morris Mano.pdf
Project_Mgmt_Institute_-Marc Marc Marc .pdf
Environmental studies, Moudle 3-Environmental Pollution.pptx
VTU IOT LAB MANUAL (BCS701) Computer science and Engineering
Solar energy pdf of gitam songa hemant k
Lesson 3 .pdf

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(); }
  • 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()); }
  • 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.
  • 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.
  • 40. Resources • IoScheduler/IoTransformer
 https://gist.github.com/humblerookie/9b395f653a81cca17280921175064232 • Isolates Playground
 https://github.com/humblerookie/isolates-playground/