Reputation: 81
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.
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 similar requests (that need to use current localization) in a single view.
Upvotes: 7
Views: 4294
Reputation: 503
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.
Upvotes: 3