Sobes.tech
Junior — Middle

Kas saaksite selgitada, mida tähendab BLoC muster rakenduse arhitektuuris?

sobes.tech AI

Vastus AI-lt

The BLoC (Business Logic Component) pattern in Flutter application architecture is designed to separate business logic from the UI. It helps manage the application's state, making the code more modular and testable.

Main ideas of BLoC:

  • Data streams (Streams): BLoC uses streams to transmit events from the UI and emit states back.
  • Input events (Events): The UI sends events to the BLoC, such as a button press.
  • Output states (States): The BLoC processes events and emits new states, which the UI subscribes to.

Example of a simple BLoC in Dart:

import 'dart:async';

class CounterBloc {
  int _counter = 0;

  final _stateController = StreamController<int>();
  Stream<int> get counterStream => _stateController.stream;

  final _eventController = StreamController<void>();
  Sink<void> get incrementSink => _eventController.sink;

  CounterBloc() {
    _eventController.stream.listen((_) {
      _counter++;
      _stateController.sink.add(_counter);
    });
  }

  void dispose() {
    _stateController.close();
    _eventController.close();
  }
}

Here, the UI sends an event to incrementSink, the BLoC increments the counter and sends the new value to the counterStream, which the UI subscribes to.