Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where and when should I store values in BLoC itself or its state

Context

I come from Redux and I am learning the BLoC pattern for global state management. I am having troubles defining where should I store values as properties inside the BLoC class, and when I should store values inside States.

Use case

I have a home page where I show some Ads, depending on its category (category should never be null). I implemented an AdsBloc like this:

class AdsBloc extends Bloc<AdsEvent, AdsState> {
  final AdsRepository repository;
  AdsBloc({@required this.repository})
      : super(AdsInitial(category: Category.DOGS));

  @override
  Stream<AdsState> mapEventToState(
    AdsEvent event,
  ) async* {
    // my code
  }
}

And these are my AdsState:

abstract class AdsState {
  final Category category;
  AdsState({this.category});
}

class AdsInitial extends AdsState {
  AdsInitial({category}) : super(category: category);
}

class AdsSuccess extends AdsState {
  final PaginatedAds paginatedAds;
  AdsSuccess({this.paginatedAds, category}) : super(category: category);
}

class AdsFailure extends AdsState {
  AdsFailure({category}) : super(category: category);
}

Problem

Because of the way I implemented the pattern, I need to pass the category every time I change the state.

Solution?

So I was thinking if I can consider the category property to be of AdsBloc and remove it from state, this way I can get a better control of this property.

like image 826
Raul Mabe Avatar asked Nov 16 '22 06:11

Raul Mabe


1 Answers

Implement "category" as a parameter for the event that is triggering ad loading process. This way, for example, you will tell BLoC to "LoadAds" with "category: Category.DOGS".

class LoadAds extends AdsEvent {
  final Category category;
  
  LoadAds({
    @required this.category,
  });

  @override
  List<Object> get props => [category];
}

This way you will be able to use single bloc instance to load different ad types when needed. Load DOGS first, 2 minutes later load CATS instead of dogs.
If you do not need this ability - then defining category inside bloc itself is perfectly fine.

like image 126
Thepeanut Avatar answered Dec 05 '22 13:12

Thepeanut