Skip to content

Commit

Permalink
keep initialized state
Browse files Browse the repository at this point in the history
i wanted to avoid needing to have the setup be an async function to
reduce code changes in the existing clients using the analytics
libraries, all of them are currently synchronous. Since the analytics
class stores an instance of each provider, adding the initialized flag
should work to prevent needing to call the Segment config method every
single time.
  • Loading branch information
claude committed Mar 8, 2023
1 parent b81778f commit ed5a6ac
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/flutter_app_analytics_segment_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,20 @@ class SegmentProvider implements AnalyticsProvider {
String _writeKey = '';
String? _userId;

bool _initialized = false;

SegmentProvider({
required String writeKey,
String? userId,
}) {
_writeKey = writeKey;
_userId = userId;
}

initialize() async {
if (_initialized) {
return;
}
await Segment.config(
options: SegmentConfig(
writeKey: _writeKey,
Expand All @@ -24,13 +30,15 @@ class SegmentProvider implements AnalyticsProvider {
debug: false,
),
);
_initialized = true;
}

@override
Future<void> identify({
String? userId,
Map<String, dynamic>? properties,
}) async {
initialize();
if (userId != null && properties != null) {
await Segment.identify(userId: _userId, traits: properties);
} else if (userId != null) {
Expand All @@ -42,11 +50,13 @@ class SegmentProvider implements AnalyticsProvider {

@override
Future<void> trackEvent(AnalyticsEvent event) async {
initialize();
await Segment.track(eventName: event.name, properties: event.properties);
}

@override
Future<void> trackEvents(List<AnalyticsEvent> events) async {
initialize();
await Future.forEach<AnalyticsEvent>(events, (event) => trackEvent(event));
}
}

0 comments on commit ed5a6ac

Please sign in to comment.