felangel / bloc

A predictable state management library that helps implement the BLoC design pattern
https://bloclibrary.dev
MIT License
11.76k stars 3.39k forks source link

question: is this considered a anti pattern if a repository depends on another bloc. #4173

Closed talpx0 closed 4 months ago

talpx0 commented 4 months ago

Description

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<ThemeCubit>(create: (context) => ThemeCubit()),
        BlocProvider<WeatherProviderCubit>(create: (context) => WeatherProviderCubit()),
      ],
      child: BlocBuilder<WeatherProviderCubit, WeatherProviderState>(
        builder: (context, state) {
          return MultiRepositoryProvider(
            providers: [
              RepositoryProvider<WeatherRepository>(create: (context) => WeatherRepository(state.provider)),
            ],
            child: Container(
              child: Center(child: Text('Weather App')),
            ),
          );
        },
      ),
    );
  }
}

here WeatherRepository is depending on weather bloc , later another bloc gonna use WeatherRepository ? is this considered as anit pattern or not ?

felangel commented 4 months ago

Hi @talpx0 👋 Thanks for opening an issue!

While there are always exceptions, I generally would consider it an anti-pattern to have a repository depend on a bloc because repositories (as described in the architecture docs) are part of the domain layer whereas blocs are part of the application layer and the application layer should depend on the domain layer not the other way around.

Screenshot 2024-05-22 at 10 24 05 PM

Hope that helps!

talpx0 commented 4 months ago

Hi @talpx0 👋 Thanks for opening an issue!

While there are always exceptions, I generally would consider it an anti-pattern to have a repository depend on a bloc because repositories (as described in the architecture docs) are part of the domain layer whereas blocs are part of the application layer and the application layer should depend on the domain layer not the other way around.

Screenshot 2024-05-22 at 10 24 05 PM

Hope that helps!

Thanks for replying. I actually can't find a better way than this. Let's say you have three repositories, each with an enum relationship, but their underlying models are not the same. For example, AModel uses "Fahrenheit", BModel uses "Celsius", and CModel uses "Kelvin". I have to choose one of them based on the provider (as the user can switch the provider they want). No matter if I try to use listeners or repository injection, I can't avoid letting the state determine the repository. Furthermore, this wouldn't cause any performance issues or other problems, right?