startCommunicationChannel method

  1. @override
FutureOr<bool> startCommunicationChannel(
  1. NearbyCommunicationChannelData data
)
override

Starts listening for messages from device with NearbyCommunicationChannelData.connectedDeviceId.

Implementation

@override
FutureOr<bool> startCommunicationChannel(
  NearbyCommunicationChannelData data,
) async {
  Logger.debug('Creating messages subscription');
  _stateController.add(CommunicationChannelState.loading);

  await endCommunicationChannel();
  final eventListener = data.messagesListener;
  final filesListener = data.filesListener;
  _messagesSubscription = NearbyServiceIOSPlatform.instance.messagesStream
      .where((event) => event != null)
      .map(MessagesStreamMapper.toMessage)
      .where((event) => event?.sender.id == data.connectedDeviceId)
      .cast<ReceivedNearbyMessage>()
      .listen(
    eventListener.onData,
    onDone: () {
      _stateController.add(CommunicationChannelState.notConnected);
      eventListener.onDone?.call();
    },
    onError: (e, s) {
      Logger.error(e);
      _stateController.add(CommunicationChannelState.notConnected);
      eventListener.onError?.call(e, s);
    },
    cancelOnError: eventListener.cancelOnError,
  );
  _resourcesSubscription = NearbyServiceIOSPlatform.instance.resourcesStream
      .map(ResourcesStreamMapper.toFilesPack)
      .where((event) => event != null)
      .cast<ReceivedNearbyFilesPack>()
      .listen(
    (e) => filesListener?.onData.call(e),
    onDone: filesListener?.onDone,
    onError: (e, s) {
      Logger.error(e);
      _stateController.add(CommunicationChannelState.notConnected);
      filesListener?.onError?.call(e, s);
    },
    cancelOnError: filesListener?.cancelOnError,
  );
  if (_messagesSubscription != null) {
    Logger.info('Messages subscription was created successfully');
    eventListener.onCreated?.call();
    _stateController.add(CommunicationChannelState.connected);
  } else {
    _stateController.add(CommunicationChannelState.notConnected);
  }
  if (_resourcesSubscription != null) {
    Logger.info('Resources subscription was created successfully');
  }

  return true;
}