6

i'm working on an application that uses cubits, to manage the state. Very often when i need to make an api request i need to get my current localization (handle possible exceptions) and then send it to backend. So i guess i should use cubit for the requests and for getting my current localization. So now my question is how should i handle that? Can i somehow call gpsLocalizationCubit from another cubit? Should i call gpsLocalizationCubit and on success call requestCubit with the use of bloc listener? But then how should i manage loading screen that should be visible for both getting localization and api request? Another problem is that i have multiple similiar request (that need to use current localization) in single view.

Thanks for the answers :D

Nepath
  • 61
  • 3

1 Answers1

1

The best way to communicate between Blocs or Cubits is to pass their stream as a parameter. In your cas you could implement something like that:

class LocationCubit extends Cubit<LocationData> {
  ...
}

class SomeCubit extends Cubit<SomeState> {
  final StreamSubscription _locationSubscription;

  SomeCubit({required Stream<LocationData> locationStream}) {
    _locationSubscription = locationStream.listen((locationData) {
      // update your state with the new location or do something
    });
  }

  @override
  Future<void> close() {
    _locationData.cancel();
    super.close();
  }
}

// Where you create your Cubits:
final locationCubit = LocationCubit();
final myCubit = SomeCubit(locationStream: locationCubit.stream);

That way you will not have any direct dependency between your Cubit classes.

An other way could be to listen for location changes by using the location package https://pub.dev/packages/location in some kind of manager. This manager could be a singleton that you inject with GetIt for example, so you can mock it in your tests.

Tijee
  • 388
  • 3
  • 12