Skip to main content

๐Ÿงฉ BLoC Architecture Guide

Guide lengkap untuk implementasi BLoC (Business Logic Component) pattern di MStore Mobile dengan proper scope dan lifecycle management.

๐Ÿ“Œ Prinsip Dasar

Siapa yang Memiliki State?

BLoC bukan sekadar โ€œcontrollerโ€ โ€” dia pemilik state dan event lifecycle.Pertanyaannya bukan โ€œdi mana paling mudahโ€, tapi siapa yang bertanggung jawab mengelola durasi hidup state itu.

โš™๏ธ Hierarki UI dan Scope yang Tepat

Tabel Scope BLoC


๐Ÿงฉ Best Practice BLoC Scope per Domain

Global / Persistent

Scope: Root (di MaterialApp)Contoh:
  • AuthBloc
  • SettingsBloc
  • ThemeBloc

Feature-based

Scope: RouteContoh:
  • SalesBloc
  • InventoryBloc
  • HRBloc

Ephemeral UI

Scope: Page / Widget StateContoh:
  • FilterCubit
  • TabIndexCubit
  • DialogCubit
Gunakan Cubit untuk state lokal kecil, bukan Bloc penuh.โ€œGunakan BLoC untuk domain state, Cubit untuk UI state.โ€

๐Ÿง  Struktur Ideal (Modular + Feature Scoped)


๐Ÿ”ง Implementation Pattern

โœ… CORRECT: Route-Level BlocProvider

Benefits:
  • โœ… AuthBloc hanya hidup selama route aktif
  • โœ… Semua widget di bawah LoginPage bisa context.watch<AuthBloc>()
  • โœ… Tidak membanjiri global scope
  • โœ… Auto-disposed saat keluar route

โŒ ANTIPATTERN: Page-Level BlocProvider

Problems:
  • โŒ Setiap kali route direpush, SalesBloc direcreate
  • โŒ Request API ulang
  • โŒ State hilang saat navigasi antar tab
  • โŒ Tidak bisa share state ke sub-page (/sales/detail/:id)

๐Ÿงฎ MultiBloc Pattern

Jika satu feature butuh beberapa state domain:
Results:
  • โœ… Semua anak widget bisa akses multi-state
  • โœ… Masih terisolasi dalam feature route
  • โœ… Lifecycle otomatis dihapus saat keluar route

๐Ÿงฑ Decision Matrix

  • State domain / API calls
  • Perlu diakses antar sub-page
  • Misal: Sales, Inventory, HR
  • Lifecycle: Lives as long as route lives

โœ… Implementation Checklist

1

Define BLoC Scope

Tentukan apakah state ini:
  • Global (auth, theme)
  • Feature-level (sales, inventory)
  • UI-only (filter, sort)
2

Create BLoC/Cubit

3

Register in DI

4

Provide at Route Level

5

Access in Widgets


๐Ÿ“Š Architecture Summary


๐Ÿ’ก Key Takeaways

BLoC Domain

Di route-level (feature provider)Contoh: /sales, /inventory

Cubit Ringan

Di page/component levelContoh: Filter, Sort, Tab Index

Root BLoC

Hanya untuk global shared stateContoh: Auth, Theme, Locale

Never in Component

Jangan taruh BLoC di widget kecilAkan recreate setiap build

Mobile Architecture

Complete mobile architecture guide

State Management

State management patterns

Dependency Injection

DI setup dengan Injectable

Testing BLoC

Unit testing untuk BLoC

Best Practice: Selalu provide BLoC di route-level untuk proper lifecycle management dan avoid memory leaks.
Avoid: Jangan provide BLoC di component-level widget. Ini akan cause recreate setiap rebuild dan memory issues.