SlideShare a Scribd company logo
Async flow control
with Redux Sagas
Pedro Solá @ 8fit
Sagas
- Write & reason about asynchronous code 

as if it was synchronous code
- Test like a boss
- Complex composition. (fork, cancel, join,
race, throttling)
Side effect
management
Action Middleware Reducers
• redux-thunk
• redux-sagas
State
- Generators
- Declarative effects
Sagas
The mental model is that a saga is like a separate thread in your
application that's solely responsible for side effects.
This thread can be started, paused and cancelled from the main
application with normal redux actions.
Generators
Specified by the function* declaration
Generators can suspend themselves
A generator will be suspended on the
yield keyword, returning control to the
callee.
Declarative Effects
You can view Effects like instructions to the middleware
to perform some operation (invoke some asynchronous
function, dispatch an action to the store).
{ '@@redux-saga/IO': true,
CALL: { context: null, fn: [Function], args: [ 1, 2, 3 ] } }
Timer app
example from: https://jaysoo.ca/2016/01/03/managing-processes-in-redux-using-sagas/
State machineInterface
No middleware
class Timer extends Component {
componentWillReceiveProps(nextProps) {
const { state: { status: currStatus } } = this.props;
const { state: { status: nextStatus } } = nextProps;
if (currState === 'Stopped' && nextState === 'Running') {
this._startTimer();
} else if (currState === 'Running' && nextState === 'Stopped') {
this._stopTimer();
}
}
_startTimer() {
this._intervalId = setInterval(() => {
this.props.tick();
}, 1000);
}
_stopTimer() {
clearInterval(this._intervalId);
}
// ...
}
Thunk
export default {
start: () => (
(dispatch, getState) => {
// This transitions state to Running
dispatch({ type: 'START' });
// Check every 1 second if we are still Running.
// If so, then dispatch a `TICK`, otherwise stop
// the timer.
const intervalId = setInterval(() => {
const { status } = getState();
if (status === 'Running') {
dispatch({ type: 'TICK' });
} else {
clearInterval(intervalId);
}
}, 1000);
}
)
// ...
};
Saga
function* runTimer() {
// The sagasMiddleware will start running this generator.
// Wake up when user starts timer.
while(yield take('START')) {
while(true) {
const { stop, timer } = yield race({
stop: take('STOP'),
timer: call(delay, ONE_SECOND),
});
// if the stop action has been triggered first,
// break out of the timer loop
if (stop) {
break;
} else {
yield put(actions.tick());
}
}
}
}
Testing
it('should cancel the timer after a STOP action', => {
const generator = runTimer(); // create the generator object
let next = generator.next(); // step into
// the generator is now suspended, waiting for a START
expect(next).toEqual(take('START'));
next = generator.next({ type: 'START' });
const timerRace = race({
stop: take('STOP'),
timer: call(delay, ONE_SECOND),
});
expect(next).toEqual(timerRace);
// let's trigger stop before the timer completes
next = generator.next({ type: 'STOP' });
// we expect the runTimer to be awaiting a START action now
expect(next).toEqual(take('START'));
});
Common uses
- API calls
- Data sync
- Business logic services
- Orchestration of components across
multiple screens in your applications
Summary
IMO despite being initially intimidating,
expressing asynchronous logic in sagas
feels very natural, and is very powerful.
pedro@8fit.com
pssssssst! upgrade your life! come work with these beautiful people
Thanks for listening ❤

More Related Content

What's hot

React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
Clickky
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
Visual Engineering
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
DreamLab
 
React & Redux
React & ReduxReact & Redux
React & Redux
Federico Bond
 
Workshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte II
Visual Engineering
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Better React state management with Redux
Better React state management with ReduxBetter React state management with Redux
Better React state management with Redux
Maurice De Beijer [MVP]
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
DreamLab
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
FITC
 
Evan Schultz - Angular Camp - ng2-redux
Evan Schultz - Angular Camp - ng2-reduxEvan Schultz - Angular Camp - ng2-redux
Evan Schultz - Angular Camp - ng2-reduxEvan Schultz
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and Redux
Thom Nichols
 
Let's Redux!
Let's Redux!Let's Redux!
Let's Redux!
Joseph Chiang
 
React hooks
React hooksReact hooks
React hooks
Assaf Gannon
 
React lecture
React lectureReact lecture
React lecture
Christoffer Noring
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
Nir Kaufman
 
Redux training
Redux trainingRedux training
Redux training
dasersoft
 
React redux
React reduxReact redux
React redux
Michel Perez
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max Petruck
Maksym Petruk
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
Ignacio Martín
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
Vedran Blaženka
 

What's hot (20)

React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
Workshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte II
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Better React state management with Redux
Better React state management with ReduxBetter React state management with Redux
Better React state management with Redux
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 
Evan Schultz - Angular Camp - ng2-redux
Evan Schultz - Angular Camp - ng2-reduxEvan Schultz - Angular Camp - ng2-redux
Evan Schultz - Angular Camp - ng2-redux
 
ProvJS: Six Months of ReactJS and Redux
ProvJS:  Six Months of ReactJS and ReduxProvJS:  Six Months of ReactJS and Redux
ProvJS: Six Months of ReactJS and Redux
 
Let's Redux!
Let's Redux!Let's Redux!
Let's Redux!
 
React hooks
React hooksReact hooks
React hooks
 
React lecture
React lectureReact lecture
React lecture
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
 
Redux training
Redux trainingRedux training
Redux training
 
React redux
React reduxReact redux
React redux
 
React, Redux, ES2015 by Max Petruck
React, Redux, ES2015   by Max PetruckReact, Redux, ES2015   by Max Petruck
React, Redux, ES2015 by Max Petruck
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 

Viewers also liked

The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
Daniel Franz
 
7 Redux challenges
7 Redux challenges7 Redux challenges
7 Redux challenges
reactima
 
Flossuk17 introduction to ovirt
Flossuk17 introduction to ovirtFlossuk17 introduction to ovirt
Flossuk17 introduction to ovirt
Freddy Rolland
 
Carta de MORENA al comisionado de la ONU para los Derechos Humanos
Carta de MORENA al comisionado de la ONU para los Derechos Humanos Carta de MORENA al comisionado de la ONU para los Derechos Humanos
Carta de MORENA al comisionado de la ONU para los Derechos Humanos
AMLO-MORENA
 
Everything You Wanted to Know About LinkedIn, but Were Too Embarrassed to Ask
Everything You Wanted to Know About LinkedIn, but Were Too Embarrassed to AskEverything You Wanted to Know About LinkedIn, but Were Too Embarrassed to Ask
Everything You Wanted to Know About LinkedIn, but Were Too Embarrassed to Ask
Jonathan Rick
 
Smart Attribution + Cross Device - #SMXMunich 2017 - www.cubed.ai
Smart Attribution + Cross Device - #SMXMunich 2017 - www.cubed.aiSmart Attribution + Cross Device - #SMXMunich 2017 - www.cubed.ai
Smart Attribution + Cross Device - #SMXMunich 2017 - www.cubed.ai
Russell McAthy
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient Data
Carol McDonald
 
ENDOCA presentazione azienda e prodotti
ENDOCA presentazione azienda e prodottiENDOCA presentazione azienda e prodotti
ENDOCA presentazione azienda e prodotti
Alesh Trcek
 
10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
 10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot 10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
HubSpot
 
How to Earn the Attention of Today's Buyer
How to Earn the Attention of Today's BuyerHow to Earn the Attention of Today's Buyer
How to Earn the Attention of Today's Buyer
HubSpot
 
Modern Prospecting Techniques for Connecting with Prospects (from Sales Hacke...
Modern Prospecting Techniques for Connecting with Prospects (from Sales Hacke...Modern Prospecting Techniques for Connecting with Prospects (from Sales Hacke...
Modern Prospecting Techniques for Connecting with Prospects (from Sales Hacke...
HubSpot
 
Class 1: Email Marketing Certification course: Email Marketing and Your Business
Class 1: Email Marketing Certification course: Email Marketing and Your BusinessClass 1: Email Marketing Certification course: Email Marketing and Your Business
Class 1: Email Marketing Certification course: Email Marketing and Your Business
HubSpot
 
Behind the Scenes: Launching HubSpot Tokyo
Behind the Scenes: Launching HubSpot TokyoBehind the Scenes: Launching HubSpot Tokyo
Behind the Scenes: Launching HubSpot Tokyo
HubSpot
 
HubSpot Diversity Data 2016
HubSpot Diversity Data 2016HubSpot Diversity Data 2016
HubSpot Diversity Data 2016
HubSpot
 
Why People Block Ads (And What It Means for Marketers and Advertisers) [New R...
Why People Block Ads (And What It Means for Marketers and Advertisers) [New R...Why People Block Ads (And What It Means for Marketers and Advertisers) [New R...
Why People Block Ads (And What It Means for Marketers and Advertisers) [New R...
HubSpot
 
What is Inbound Recruiting?
What is Inbound Recruiting?What is Inbound Recruiting?
What is Inbound Recruiting?
HubSpot
 
3 Proven Sales Email Templates Used by Successful Companies
3 Proven Sales Email Templates Used by Successful Companies3 Proven Sales Email Templates Used by Successful Companies
3 Proven Sales Email Templates Used by Successful Companies
HubSpot
 
Add the Women Back: Wikipedia Edit-a-Thon
Add the Women Back: Wikipedia Edit-a-ThonAdd the Women Back: Wikipedia Edit-a-Thon
Add the Women Back: Wikipedia Edit-a-Thon
HubSpot
 
Design in Tech Report 2017
Design in Tech Report 2017Design in Tech Report 2017
Design in Tech Report 2017
John Maeda
 

Viewers also liked (19)

The redux saga begins
The redux saga beginsThe redux saga begins
The redux saga begins
 
7 Redux challenges
7 Redux challenges7 Redux challenges
7 Redux challenges
 
Flossuk17 introduction to ovirt
Flossuk17 introduction to ovirtFlossuk17 introduction to ovirt
Flossuk17 introduction to ovirt
 
Carta de MORENA al comisionado de la ONU para los Derechos Humanos
Carta de MORENA al comisionado de la ONU para los Derechos Humanos Carta de MORENA al comisionado de la ONU para los Derechos Humanos
Carta de MORENA al comisionado de la ONU para los Derechos Humanos
 
Everything You Wanted to Know About LinkedIn, but Were Too Embarrassed to Ask
Everything You Wanted to Know About LinkedIn, but Were Too Embarrassed to AskEverything You Wanted to Know About LinkedIn, but Were Too Embarrassed to Ask
Everything You Wanted to Know About LinkedIn, but Were Too Embarrassed to Ask
 
Smart Attribution + Cross Device - #SMXMunich 2017 - www.cubed.ai
Smart Attribution + Cross Device - #SMXMunich 2017 - www.cubed.aiSmart Attribution + Cross Device - #SMXMunich 2017 - www.cubed.ai
Smart Attribution + Cross Device - #SMXMunich 2017 - www.cubed.ai
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient Data
 
ENDOCA presentazione azienda e prodotti
ENDOCA presentazione azienda e prodottiENDOCA presentazione azienda e prodotti
ENDOCA presentazione azienda e prodotti
 
10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
 10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot 10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
10 Things You Didn’t Know About Mobile Email from Litmus & HubSpot
 
How to Earn the Attention of Today's Buyer
How to Earn the Attention of Today's BuyerHow to Earn the Attention of Today's Buyer
How to Earn the Attention of Today's Buyer
 
Modern Prospecting Techniques for Connecting with Prospects (from Sales Hacke...
Modern Prospecting Techniques for Connecting with Prospects (from Sales Hacke...Modern Prospecting Techniques for Connecting with Prospects (from Sales Hacke...
Modern Prospecting Techniques for Connecting with Prospects (from Sales Hacke...
 
Class 1: Email Marketing Certification course: Email Marketing and Your Business
Class 1: Email Marketing Certification course: Email Marketing and Your BusinessClass 1: Email Marketing Certification course: Email Marketing and Your Business
Class 1: Email Marketing Certification course: Email Marketing and Your Business
 
Behind the Scenes: Launching HubSpot Tokyo
Behind the Scenes: Launching HubSpot TokyoBehind the Scenes: Launching HubSpot Tokyo
Behind the Scenes: Launching HubSpot Tokyo
 
HubSpot Diversity Data 2016
HubSpot Diversity Data 2016HubSpot Diversity Data 2016
HubSpot Diversity Data 2016
 
Why People Block Ads (And What It Means for Marketers and Advertisers) [New R...
Why People Block Ads (And What It Means for Marketers and Advertisers) [New R...Why People Block Ads (And What It Means for Marketers and Advertisers) [New R...
Why People Block Ads (And What It Means for Marketers and Advertisers) [New R...
 
What is Inbound Recruiting?
What is Inbound Recruiting?What is Inbound Recruiting?
What is Inbound Recruiting?
 
3 Proven Sales Email Templates Used by Successful Companies
3 Proven Sales Email Templates Used by Successful Companies3 Proven Sales Email Templates Used by Successful Companies
3 Proven Sales Email Templates Used by Successful Companies
 
Add the Women Back: Wikipedia Edit-a-Thon
Add the Women Back: Wikipedia Edit-a-ThonAdd the Women Back: Wikipedia Edit-a-Thon
Add the Women Back: Wikipedia Edit-a-Thon
 
Design in Tech Report 2017
Design in Tech Report 2017Design in Tech Report 2017
Design in Tech Report 2017
 

Similar to Asyc flow control with javascript generators - redux-saga

Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side Effects
GlobalLogic Ukraine
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programming
Michael Arenzon
 
Side effects-con-redux
Side effects-con-reduxSide effects-con-redux
Side effects-con-redux
Nicolas Quiceno Benavides
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
Gaurav Behere
 
The Ring programming language version 1.9 book - Part 93 of 210
The Ring programming language version 1.9 book - Part 93 of 210The Ring programming language version 1.9 book - Part 93 of 210
The Ring programming language version 1.9 book - Part 93 of 210
Mahmoud Samir Fayed
 
Productionizing spark
Productionizing sparkProductionizing spark
Productionizing spark
Sigmoid
 
The Ring programming language version 1.8 book - Part 89 of 202
The Ring programming language version 1.8 book - Part 89 of 202The Ring programming language version 1.8 book - Part 89 of 202
The Ring programming language version 1.8 book - Part 89 of 202
Mahmoud Samir Fayed
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
Christoffer Noring
 
"Angular.js Concepts in Depth" by Aleksandar Simović
"Angular.js Concepts in Depth" by Aleksandar Simović"Angular.js Concepts in Depth" by Aleksandar Simović
"Angular.js Concepts in Depth" by Aleksandar Simović
JS Belgrade
 
Sagas Middleware Architecture
Sagas Middleware ArchitectureSagas Middleware Architecture
Sagas Middleware Architecture
Mateusz Bosek
 
The Ring programming language version 1.10 book - Part 95 of 212
The Ring programming language version 1.10 book - Part 95 of 212The Ring programming language version 1.10 book - Part 95 of 212
The Ring programming language version 1.10 book - Part 95 of 212
Mahmoud Samir Fayed
 
Osol Pgsql
Osol PgsqlOsol Pgsql
Osol Pgsql
Emanuel Calvo
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
Krzysztof Szafranek
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
cbeyls
 
Timer Interceptor in Mule part 2
Timer Interceptor in Mule part 2Timer Interceptor in Mule part 2
Timer Interceptor in Mule part 2
Anirban Sen Chowdhary
 
Twin wheeler modified for arduino simplified serial protocol to sabertooth v22
Twin wheeler modified for arduino simplified serial protocol to sabertooth v22Twin wheeler modified for arduino simplified serial protocol to sabertooth v22
Twin wheeler modified for arduino simplified serial protocol to sabertooth v22
josnihmurni2907
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction ManagementUMA MAHESWARI
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
Mustafa TURAN
 

Similar to Asyc flow control with javascript generators - redux-saga (20)

Using Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side EffectsUsing Redux-Saga for Handling Side Effects
Using Redux-Saga for Handling Side Effects
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programming
 
Side effects-con-redux
Side effects-con-reduxSide effects-con-redux
Side effects-con-redux
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
The Ring programming language version 1.9 book - Part 93 of 210
The Ring programming language version 1.9 book - Part 93 of 210The Ring programming language version 1.9 book - Part 93 of 210
The Ring programming language version 1.9 book - Part 93 of 210
 
Productionizing spark
Productionizing sparkProductionizing spark
Productionizing spark
 
The Ring programming language version 1.8 book - Part 89 of 202
The Ring programming language version 1.8 book - Part 89 of 202The Ring programming language version 1.8 book - Part 89 of 202
The Ring programming language version 1.8 book - Part 89 of 202
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
"Angular.js Concepts in Depth" by Aleksandar Simović
"Angular.js Concepts in Depth" by Aleksandar Simović"Angular.js Concepts in Depth" by Aleksandar Simović
"Angular.js Concepts in Depth" by Aleksandar Simović
 
Sagas Middleware Architecture
Sagas Middleware ArchitectureSagas Middleware Architecture
Sagas Middleware Architecture
 
The Ring programming language version 1.10 book - Part 95 of 212
The Ring programming language version 1.10 book - Part 95 of 212The Ring programming language version 1.10 book - Part 95 of 212
The Ring programming language version 1.10 book - Part 95 of 212
 
Osol Pgsql
Osol PgsqlOsol Pgsql
Osol Pgsql
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
 
Module04
Module04Module04
Module04
 
Timer Interceptor in Mule part 2
Timer Interceptor in Mule part 2Timer Interceptor in Mule part 2
Timer Interceptor in Mule part 2
 
Twin wheeler modified for arduino simplified serial protocol to sabertooth v22
Twin wheeler modified for arduino simplified serial protocol to sabertooth v22Twin wheeler modified for arduino simplified serial protocol to sabertooth v22
Twin wheeler modified for arduino simplified serial protocol to sabertooth v22
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Effective Spring Transaction Management
Effective Spring Transaction ManagementEffective Spring Transaction Management
Effective Spring Transaction Management
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
 

Recently uploaded

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 

Recently uploaded (20)

GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 

Asyc flow control with javascript generators - redux-saga

  • 1. Async flow control with Redux Sagas Pedro Solá @ 8fit
  • 2. Sagas - Write & reason about asynchronous code 
 as if it was synchronous code - Test like a boss - Complex composition. (fork, cancel, join, race, throttling)
  • 3. Side effect management Action Middleware Reducers • redux-thunk • redux-sagas State
  • 4. - Generators - Declarative effects Sagas The mental model is that a saga is like a separate thread in your application that's solely responsible for side effects. This thread can be started, paused and cancelled from the main application with normal redux actions.
  • 5. Generators Specified by the function* declaration Generators can suspend themselves A generator will be suspended on the yield keyword, returning control to the callee.
  • 6. Declarative Effects You can view Effects like instructions to the middleware to perform some operation (invoke some asynchronous function, dispatch an action to the store). { '@@redux-saga/IO': true, CALL: { context: null, fn: [Function], args: [ 1, 2, 3 ] } }
  • 7. Timer app example from: https://jaysoo.ca/2016/01/03/managing-processes-in-redux-using-sagas/ State machineInterface
  • 8. No middleware class Timer extends Component { componentWillReceiveProps(nextProps) { const { state: { status: currStatus } } = this.props; const { state: { status: nextStatus } } = nextProps; if (currState === 'Stopped' && nextState === 'Running') { this._startTimer(); } else if (currState === 'Running' && nextState === 'Stopped') { this._stopTimer(); } } _startTimer() { this._intervalId = setInterval(() => { this.props.tick(); }, 1000); } _stopTimer() { clearInterval(this._intervalId); } // ... }
  • 9. Thunk export default { start: () => ( (dispatch, getState) => { // This transitions state to Running dispatch({ type: 'START' }); // Check every 1 second if we are still Running. // If so, then dispatch a `TICK`, otherwise stop // the timer. const intervalId = setInterval(() => { const { status } = getState(); if (status === 'Running') { dispatch({ type: 'TICK' }); } else { clearInterval(intervalId); } }, 1000); } ) // ... };
  • 10. Saga function* runTimer() { // The sagasMiddleware will start running this generator. // Wake up when user starts timer. while(yield take('START')) { while(true) { const { stop, timer } = yield race({ stop: take('STOP'), timer: call(delay, ONE_SECOND), }); // if the stop action has been triggered first, // break out of the timer loop if (stop) { break; } else { yield put(actions.tick()); } } } }
  • 11. Testing it('should cancel the timer after a STOP action', => { const generator = runTimer(); // create the generator object let next = generator.next(); // step into // the generator is now suspended, waiting for a START expect(next).toEqual(take('START')); next = generator.next({ type: 'START' }); const timerRace = race({ stop: take('STOP'), timer: call(delay, ONE_SECOND), }); expect(next).toEqual(timerRace); // let's trigger stop before the timer completes next = generator.next({ type: 'STOP' }); // we expect the runTimer to be awaiting a START action now expect(next).toEqual(take('START')); });
  • 12. Common uses - API calls - Data sync - Business logic services - Orchestration of components across multiple screens in your applications
  • 13. Summary IMO despite being initially intimidating, expressing asynchronous logic in sagas feels very natural, and is very powerful.
  • 14. pedro@8fit.com pssssssst! upgrade your life! come work with these beautiful people Thanks for listening ❤