Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Lidando com Efeitos Colaterais com Redux Saga
Search
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
400
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
270
Intro to Ruby
filipebarcos
1
140
Other Decks in Programming
See All in Programming
「人を評価する AI」の設計と実装
ryoyanara
0
240
コンパウンドプロダクト開発のためのローカルプロセスマネージャー再発明 #layerxgo
izumin5210
0
220
tsc.rip を支える技術 / Kyoto.なんか #8
susisu
0
160
AIに既存システムを理解させる技術 ~レガシーを見捨てないハーネスエンジニアリング入門~
ochtum
0
140
為什麼你並不需要ViewModel / No, you don't need a ViewModel
lovee
1
510
VibeCodingからAgenticWorkflowへ
starfish719
0
820
書籍「プロフェッショナルAI駆動開発」紹介スライド
juntaromatsumoto
0
450
ソフトウェアエンジニアにとっての生成AI - 特性を知って使い倒す / generative ai for software enginner
kishida
7
2.1k
仕様書を書く前にハーネスを作る - Agent Native開発は「探索を速く、判定を固く」
gotalab555
4
1.8k
in-process GraphQL のすすめ #ginzajs
izumin5210
4
1.5k
komatsuna「分散システムにおけるバグ分析手法」
komatsunaqa
0
270
My Marp Sample
sinoue0108
0
110
Featured
See All Featured
Practical Orchestrator
shlominoach
191
12k
Leo the Paperboy
mayatellez
8
2.2k
Leadership Guide Workshop - DevTernity 2021
reverentgeek
1
340
Neural Spatial Audio Processing for Sound Field Analysis and Control
skoyamalab
0
410
Unlocking the hidden potential of vector embeddings in international SEO
frankvandijk
0
900
The Cost Of JavaScript in 2023
addyosmani
55
10k
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
1
2.8k
Claude Code のすすめ
schroneko
67
230k
Groundhog Day: Seeking Process in Gaming for Health
codingconduct
0
290
Marketing to machines
jonoalderson
1
5.7k
Jamie Indigo - Trashchat’s Guide to Black Boxes: Technical SEO Tactics for LLMs
techseoconnect
PRO
0
630
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
38
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