initialize method
Initialize the chat SDK.
Must be called before using any other methods. Typically called during app startup.
Implementation
Future<void> initialize() async {
if (_isInitialized) return;
ChatLogger.info('Initializing Chat SDK');
try {
// Initialize core services
_database = await _registry.createDatabase();
_encryption = _registry.createEncryption();
await _registry.adapter.initialize();
_eventBus = ChatEventBusImpl();
_outboundQueue = OutboundQueueImpl(
adapter: _registry.adapter,
database: _database,
);
await _outboundQueue.initialize();
_syncEngine = SyncEngineImpl(
adapter: _registry.adapter,
database: _database,
eventBus: _eventBus,
);
// Listen to internal event bus and forward to public stream
_subscriptions
..add(
_eventBus.eventStream.listen(_eventController.add),
)
// Listen to identity provider and refresh user-scoped projections.
..add(
_registry.identityProvider.userIdChanges.listen(
_handleIdentityChanged,
),
)
// Listen to adapter events and process via sync engine
..add(
_registry.adapter.eventStream.listen(_handleAdapterEvent),
)
// Listen to connection state
..add(
_registry.adapter.connectionState.listen((state) {
_connectionState.value = state;
if (state == ChatConnectionState.connected) {
_sessionState.value = _sessionStateForCurrentConnection();
_syncEngine.sync();
_outboundQueue.processQueue();
startHeartbeat();
} else if (state == ChatConnectionState.disconnected) {
_sessionState.value = _sessionStateForCurrentConnection();
stopHeartbeat();
}
}),
)
// Listen to sync status
..add(
_syncEngine.syncStatus.listen((status) {
_syncStatus.value = status;
}),
)
// Listen to pending count
..add(
_outboundQueue.pendingCount.listen((count) {
_pendingCount.value = count;
}),
);
_isInitialized = true;
await _handleIdentityChanged(
await _registry.identityProvider.getCurrentUserId(),
);
ChatLogger.info('Chat SDK initialized');
} catch (e, s) {
// Clean up any subscriptions that were added before the error
ChatLogger.error('Failed to initialize Chat SDK', e, s);
await _cleanupSubscriptions();
rethrow;
}
}