Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Lidando com Efeitos Colaterais com Redux Saga
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Filipe Costa
May 13, 2017
Programming
230
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Lidando com Efeitos Colaterais com Redux Saga
Filipe Costa
May 13, 2017
More Decks by Filipe Costa
See All by Filipe Costa
Pitch - Lidando com Efeitos Colaterais com Redux Saga
filipebarcos
0
410
Rust for Rubysts
filipebarcos
2
260
Limpando Seu Código JS Com O Padrão Pub/Sub
filipebarcos
0
200
Tu trabalha em casa?? Que moleza hein!
filipebarcos
0
130
Rediscovering OOP in Rails World
filipebarcos
0
100
jQuery Bad Practices
filipebarcos
2
280
Intro to Ruby
filipebarcos
1
140
Other Decks in Programming
See All in Programming
世界の中心で、AI(App Intents)をさけぶ ー App Intents中心設計の実践ガイド
touyou
0
380
kubernetes コンポーネント開発入門 / 新卒N年目の勉強会&交流会!〜〇〇への誘い〜 #n_study
mazrean
0
200
The Good Stuff, Not the Slop: Engineering High-Quality Android Apps with Modern AI Tooling
danybony
1
240
新卒PdEのリアル
ryu1013
1
480
AWS Step Functions 大規模並列の壁を越える / jaws-sonic-2026-niigata-step-functions
kasacchiful
PRO
1
430
巨大モノリシックアプリ モダン化大作戦
ktcryomm
0
620
ゲームコントローラやキーボードのファームウェアをSwiftで書く
kishikawakatsumi
1
150
XP祭りでしか伝わらないフリップネタ #xpjug
murabayashi
0
130
思考垂れ流し開発 ~音声入力 × AIエージェント × 開発ハーネスによる試行錯誤~
npostring
0
1.1k
ALB ログから Trace を気合で繋げる技術
fohte
7
880
デプロイ直後のレイテンシスパイクを調べたら、 Railsの仕様にたどり着いた
nhsykym
0
110
コンパウンドプロダクト開発のためのローカルプロセスマネージャー再発明 #layerxgo
izumin5210
0
660
Featured
See All Featured
How STYLIGHT went responsive
nonsquared
100
6.3k
The Language of Interfaces
destraynor
162
27k
The AI Revolution Will Not Be Monopolized: How open-source beats economies of scale, even for LLMs
inesmontani
PRO
3
3.7k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
31
3.4k
Tips & Tricks on How to Get Your First Job In Tech
honzajavorek
1
730
How People are Using Generative and Agentic AI to Supercharge Their Products, Projects, Services and Value Streams Today
helenjbeal
1
310
Deep Space Network (abreviated)
tonyrice
0
300
The Spectacular Lies of Maps
axbom
PRO
1
990
How to Think Like a Performance Engineer
csswizardry
28
2.8k
Navigating Weather and Climate Data
rabernat
0
510
From Legacy to Launchpad: Building Startup-Ready Communities
dugsong
0
330
Leo the Paperboy
mayatellez
9
2.3k
Transcript
Lidando com Efeitos Colaterais com Redux Saga @filipebarcos
Redux
"Evolui ideias do Flux, mas evita suas complexidades pegando dicas
do Elm" — github.com/reactjs/redux Redux
Redux UI Reducer Store Action dispatched (currentState, action) => newState
New State
Pausa Dramática
O que é uma Função Pura?
"É uma função em que seus parâmetros são a única
coisa que influenciam no seu valor de retorno"
"É uma função em que seus parâmetros são a única
coisa que influenciam no seu valor de retorno" — eu
Redux UI Reducer Store Action dispatched (currentState, action) => newState
New State
Redux UI Middleware Reducer Store Action dispatched (currentState, action) =>
newState New State Action forwarded Action dispatched
Redux Saga
github.com/redux-saga/redux-saga
E o que é uma “Saga”?
None
“…a sequence of transactions that can be interleaved with other
transactions.” http://www.cs.cornell.edu/andru/cs711/2002fa/reading/sagas.pdf — Hector Garcia-Molina e Kenneth Salem
“…a sequence of transactions that can be interleaved with other
transactions.” http://www.cs.cornell.edu/andru/cs711/2002fa/reading/sagas.pdf — Hector Garcia-Molina e Kenneth Salem
“…a saga is like a separate thread in your application
that's solely responsible for side effects.” — https://github.com/redux-saga/redux-saga
Como eu é possível parar uma execução de uma função
em JS?
JS Generator Functions*
ES6 Feature
https://davidwalsh.name/es6-generators http://2ality.com/2015/03/es6-generators.html
https://davidwalsh.name/es6-generators function* foo(x) { const y = 2 * (yield
(x + 1)); const z = yield (y / 3); return (x + y + z); } const it = foo(5); // note: not sending anything into `next()` here console.log(it.next()); // { value:6, done:false } console.log(it.next(12)); // { value:8, done:false } console.log(it.next(13)); // { value:42, done:true }
Alguns exemplos
https://redux-saga.github.io/redux-saga/docs/basics/UsingSagaHelpers.html import { call, put } from 'redux-saga/effects'; export function*
fetchData(action) { try { const data = yield call(Api.fetchUser, action.payload.url); yield put({type: 'FETCH_SUCCEEDED', data}); } catch (error) { yield put({type: 'FETCH_FAILED', error}); } } function* watchFetchData() { yield takeEvery('FETCH_REQUESTED', fetchData); }
https://redux-saga.github.io/redux-saga/docs/basics/UsingSagaHelpers.html import { takeEvery } from 'redux-saga'; // FETCH_USERS function*
fetchUsers(action) { ... } // CREATE_USER function* createUser(action) { ... } // use them in parallel export default function* rootSaga() { yield takeEvery('FETCH_USERS', fetchUsers); yield takeEvery('CREATE_USER', createUser); }
E os testes?
import { call, put } from 'redux-saga/effects'; export function* fetchData(action)
{ try { const data = yield call(Api.fetchUser, action.payload.url); yield put({type: 'FETCH_SUCCEEDED', data}); } catch (error) { yield put({type: 'FETCH_FAILED', error}); } } function* watchFetchData() { yield takeEvery('FETCH_REQUESTED', fetchData); } https://redux-saga.github.io/redux-saga/docs/basics/UsingSagaHelpers.html
import { call, put } from 'redux-saga/effects'; export function* fetchData(action)
{ try { const data = yield call(Api.fetchUser, action.payload.url); yield put({type: 'FETCH_SUCCEEDED', data}); } catch (error) { yield put({type: 'FETCH_FAILED', error}); } } function* watchFetchData() { yield takeEvery('FETCH_REQUESTED', fetchData); } https://redux-saga.github.io/redux-saga/docs/basics/UsingSagaHelpers.html
{ CALL: { fn: Api.fetchUser, args: [“/users”], }, }
const generator = fetchData(); expect(generator.next()).toEqual({ done: false, value: call(Api.fetchUser, action.payload.url)
});
Tá, mas e aí?
redux-saga === redux-thunk + testabilidade
None
None
Ações Futuras
take x takeEvery
function* watchThis() { yield takeEvery('THIS', doThat); }
function* watchThis() { while(true) { yield take('THIS', doThat); } }
function* watchDeaths() { yield take('DIE', newTry); yield take('DIE', newTry); yield
take('DIE', put, { type: 'GAME_OVER' }); }
Chamadas “não-bloqueantes”
fork
function* mySaga() { while(true) { yield take(''); yield call(foo); yield
call(bar); } }
function* mySaga() { while(true) { yield take(''); yield fork(foo); yield
fork(bar); } }
Executar tarefas em paralelo
const [visits, registrations] = yield all([ call(fetch, '/visits'), call(fetch, '/registrations')
]);
Corrida entre efeitos colaterais
const { posts, timeout } = yield race({ posts: call(fetch,
'/posts'), timeout: call(delay, 1000) });
Composição de Sagas
yield*
function* foo() { ... } function* bar() { ... }
function* baz() { ... } function* fooBarBaz() { yield* foo(); yield* bar(); yield* baz(); }
tests?
tests?
function* foo() { ... } function* bar() { ... }
function* baz() { ... } function* fooBarBaz() { yield call(foo); yield fork(bar); yield call(baz); }
Cancelamento de Tarefas
function* mySync() { try { while(true) { yield put({type: 'SYNC_STARTED'});
const result = yield call(syncMyFiles); yield call(delay, 500); } } finally { if (yield cancelled()) yield put({ type: 'SYNC_STOPED'}); } } function* myDropbox() { while(yield take('START_FILE_SYNC')) { const mySyncTask = yield fork(mySync); yield take('STOP_FILE_SYNC'); // this will cause the forked task to jump into its finally block yield cancel(mySyncTask); } }
gist.github.com/filipebarcos/ 0a137d6ca837c117f999958a365fc5b6
Obrigado. @filipebarcos