Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RxJSで状態を管理する / state management by RxJS

adwd
May 23, 2018

RxJSで状態を管理する / state management by RxJS

adwd

May 23, 2018
Tweet

More Decks by adwd

Other Decks in Programming

Transcript

  1. const obs1 = Rx.Observable.interval(1000); obs1.subscribe(count => console.log(‘count: ‘ + count));

    // count: 1 // count: 2 // count: 3 const obs2 = Rx.Observable.fromEvent(document.body, ‘click') obs2.pipe( map(ev => ({ x: ev.clientX, y: ev.clientY })), filter(pos => pos.x > 400), ).subscribe(ev => console.log(ev)) // { x: 1000, y: 1000 } // { x: 1000, y: 200 } ͸ग़ྗ͞Εͳ͍ Observable
  2. Subject const myEvent = new Subject(); myEvent.subscribe(ev => console.log(‘event: ‘

    + ev)); myEvent.next(‘hi’) // event: hi myEvent.next(‘yo’) // event: yo
  3. BehaviorSubject // ॳظ஋ΛίϯετϥΫλͷҾ਺ʹऔΔɹ const myTodos = new BehaviorSubject([]); myTodos.subscribe(todos =>

    console.log(‘todos: ‘ + todos.length)); // todos: 0 // subscribeͨ͠ॠؒ஋͕ྲྀΕͯ͘Δ myTodos.next([ { id: 1, text: ‘do something’ } ]); // todos: 1
  4. BehaviorSubject = Flux • BehaviorSubject͕΄΅Flux(Redux)Λ΍ͬͯ͘ΕΔ • BS#next => action •

    BS#subscribe => connect(react-redux) • combineLatest => combineReducers • (BehaviorSubject͡Όͳͯ͘Observableʹͳ Δ)
  5. create-subscription example import { createSubscription } from ‘create-subscription’; const BehaviorSubscription

    = createSubscription({ getCurrentValue: behaviorSubject => behaviorSubject.getValue(), subscribe: (behaviorSubject, callback) => { const subscription = behaviorSubject.subscribe(callback); return () => subscription.unsubscribe(); } }); <BehaviorSubscription source={myTodos}> {todos => <TodoList todos={todos} /> </BehaviorSubscription>
  6. Todomvc const todos = new BehaviorSubject([]); const addTodo = text

    => { const current = todos.getValue(); todos.next([…current, { text, id: newId() }]); }; const filter = new BehaviorSubject(‘all’); // all, active, completed const filteredTodos = combineLatest(todos, filter) .pipe(map(v => switch(v.filter) { case ‘all’: return todos; case ‘active: return todos.filter(t => !t.completed); … })) <Todos todos={filteredTodos} onFilterChange={filter.next} addTodo={addTodo} />
  7. search w/ throttling const searchText = new BehaviorSubject(‘’); const searchResults

    = searchText.pipe( debounceTime(1000), switchMap(text => fetch(`/search?q=${text}`)) ) <SearchTextInput onChange={text => searchText.next(text)} /> <SearchResults results={searchResults} />
  8. ·ͱΊ • ࢓ࣄͰRedux -> RxJSʹ͍ͯͨ͠ • ࣗ෼ͱͯ͠͸͘͢͝ྑ͘ͳͬͨ • Ҿ͖ܧ͍ͩΤϯδχΞ͕RxJS஌Βͳ͍৔߹… •

    GoogleͷAdWordsνʔϜ͕Flutter/AngularDartͰࣅͨΑ ͏ͳ͜ͱ(BLoC)΍ͬͯͨ • DartConf, Google I/O 2018ʹτʔΫ͕͋Δ