Bloc: How bloc communicate in a Flutter flutter_bloc tree structure?

Created on 30 Oct 2019  路  4Comments  路  Source: felangel/bloc

I have some dilemma: I have a AuthBloc(lift state up) witch is on top of the tree, down comes other blocs for profile, products, etc. When an event is launched to ProfileBloc/PostBlocs... some usecase is executed, that uses the repositories. The problem is that if I get back from repository/usecase an 401 error how do you think is the best way to "tell" this to AuthBloc (because it handles the authentication state)?

  1. Any sub blocs is getting e reference to AuthBloc, when 401 comes call auth.logoutEvent()
  2. Creating a AppEventsService (injected using get_it) that is listen by AuthBloc, and then calls logoutEvent()
  3. Adding an interceptor to Dio (http) with AppEventsService that is listen by AuthBloc (somehow I think this breaks the clean architecture)

Any other suggestion ?

question

Most helpful comment

All is clear now, thank you for the quick and concise answer :).

All 4 comments

Hi @cosinus84 馃憢
Thanks for opening an issue!

In this case, I would recommend structuring your initialization like:

final ApiClient = ApiClient(onRevoke: () => authBloc.add(Logout()));

That way your ApiClient can handle the token management internally and surface a 401 to the caller. From the caller's context you can add the Logout event to the AuthBloc.

Hope that helps 馃憤

Thank you for your quick answer, I am trying to understand how to connect all the pieces.

  1. By saying "From the caller's context you can add the Logout event to the AuthBloc" you mean that on return 401, the caller(XYZBloc) can "call"(mapEventToState) the apiClient.onRevoke().

  2. Where does "final ApiClient = ApiClient(onRevoke: () => authBloc.add(Logout()));" goes ? inside XYZBloc ?

@cosinus84 no problem! I was referring to doing it at your initialization stage of your application.

// main.dart

void main() {
  var AuthBloc authBloc;
  final ApiClient apiClient = ApiClient(onRevoke: () => authBloc.add(Logout()));
  final Repository repo = Repository(apiClient);
  authBloc = AuthBloc(repo);

  ...

  runApp(
    BlocProvider.value(
      value: authBloc,
      child: MyApp(),
    ),
  );
}

Let me know if that helps 馃憤

All is clear now, thank you for the quick and concise answer :).

Was this page helpful?
0 / 5 - 0 ratings