startSession method

Stream<SessionEvent> startSession(
  1. SessionConfig config
)

Start a watch session with the given config.

Returns a broadcast stream of SessionEvents. The same events are also emitted on events.

Throws StateError if a session is already active.

Implementation

Stream<SessionEvent> startSession(SessionConfig config) {
  if (_session == null) {
    throw StateError(
      'WatchSessionModule not initialized. Call initialize() first.',
    );
  }
  if (_activeSessionId != null) {
    throw StateError(
      'A watch session is already active (id: $_activeSessionId). '
      'Stop it before starting a new one.',
    );
  }

  _activeSessionId = config.sessionId;
  SynheartLogger.log(
    '[WatchSessionModule] Starting session ${config.sessionId} '
    '(mode: ${config.mode.value}, duration: ${config.durationSec}s)',
  );

  final stream = _session!.startSession(config);

  _activeSubscription = stream.listen(
    (event) {
      if (!_eventController.isClosed) {
        _eventController.add(event);
      }

      if (event is SessionSummary || event is SessionError) {
        SynheartLogger.log(
          '[WatchSessionModule] Session ${event.sessionId} ended '
          '(${event.runtimeType})',
        );
        _cleanup();
      }
    },
    onError: (Object error) {
      SynheartLogger.log(
        '[WatchSessionModule] Stream error: $error',
        error: error,
      );
      if (!_eventController.isClosed) {
        _eventController.addError(error);
      }
    },
    onDone: _cleanup,
  );

  return _eventController.stream;
}