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

BLoC Pattern Introduction with Swift

to4iki
January 20, 2019

BLoC Pattern Introduction with Swift

# TL;DL
BLoC is (Flutter発祥の)状態管理に関する軽量アーキテクチャパターン

# SeeAlso
- https://qiita.com/kabochapo/items/8738223894fb74f952d3
- https://medium.com/flutter-jp/bloc-provider-70e869b11b2f

to4iki

January 20, 2019
Tweet

More Decks by to4iki

Other Decks in Programming

Transcript

  1. Guideline 1 1. BLoCͷೖग़ྗΠϯλʔϑΣʔε͸͢΂ͯ Stream/Sink Ͱ͋ Δ 2. BLoCͷґଘ͸ඞͣ஫ೖՄೳͰɺ؀ڥʹґଘ͠ͳ͍ 3.

    BLoC಺ʹ؀ڥ͝ͱͷ৚݅෼ذ͸࣋ͨͳ͍ 4. Ҏ্ͷϧʔϧʹै͏ݶΓɺଞͷ࣮૷ΛͲ͏͢Δ͔͸໰Θͳ͍ 1 https://github.com/tenhobi/flashcards/issues/12#issuecomment-373922966 11
  2. e.g. Dart class Bloc { final emailController = StreamController<String>(); //

    Add data to stream get changeEmail => emailController.sink.add; // Retrieve data from stream get email => emailController.stream; } void main() { final bloc = Bloc(); bloc.email.listen((value) { print(value); }); bloc.changeEmail("NEW EMAIL"); } 14
  3. e.g. Swift final class TaskBloc { /// input let addTask

    = PublishRelay<Task>() /// output var tasks: Observable<[Task]> { return _tasks.asObservable() } private let _tasks = BehaviorRelay<[Task]>(value: []) private let disposeBag = DisposeBag() init() { addTask .withLatestFrom(tasks) { ($0, $1) } .map { [$0] + $1 } .bind(to: _tasks) .disposed(by: disposeBag) } } 16
  4. e.g. Swift taskBlock.tasks .subscribe(onNext: { tasks in print(tasks) }) .disposed(by:

    disposeBag) addButton.rx.tap .throttle(0.5, latest: false, scheduler: ConcurrentMainScheduler.instance) .map { Task(name: "task_01") } .bind(to: taskBlock.addTask) .disposed(by: disposeBag) 17
  5. Flutter.widgets.InheritedWidget3 Base class for widgets that efficiently propagate information down

    the tree. To obtain the nearest instance of a particular type of inherited widget from a build context, use BuildContext.inheritFromWidgetOfExactType. 3 https://docs.flutter.io/flutter/widgets/InheritedWidget-class.html 24
  6. e.g. Flutter class BlocProvider extends InheritedWidget { BlocProvider({Key key, Widget

    child}) : super(key: key, child: child); Bloc get bloc => Bloc(); @override bool updateShouldNotify(_) => true; // BlocProviderʹैଐ͢ΔWidgetͰ͜ͷϝιουΛ࢖͑͹BlocProviderͷΠϯελϯε͕ಘΒΕ // ͦΕΛ࢖ͬͯBlocͷΠϯελϯε΋ಘΒΕΔ static BlocProvider of(BuildContext context) { return (context.inheritFromWidgetOfExactType(BlocProvider) as BlocProvider); } } 26
  7. e.g. Swift ※ ΠϝʔδΛ௫ΉͨΊͷٖࣅίʔυͰ͢ final class BlocProvider<T> { let block:

    T static func of(_ view: UIView) -> TaskBloc { // Ҿ਺view͔Βଐ͢Δ `BLoC` Λ୳ࡧ͢Δ fatalError("implement") } } 28