in lib/src/multi_channel.dart [173:215]
VirtualChannel<T> virtualChannel([int? id]) {
int inputId;
int outputId;
if (id != null) {
// Since the user is passing in an id, we're connected to a remote
// VirtualChannel. This means messages they send over this channel will
// have the original odd id, but our replies will have an even id.
inputId = id;
outputId = id + 1;
} else {
// Since we're generating an id, we originated this VirtualChannel. This
// means messages we send over this channel will have the original odd id,
// but the remote channel's replies will have an even id.
inputId = _nextId + 1;
outputId = _nextId;
_nextId += 2;
}
// If the inner channel has already closed, create new virtual channels in a
// closed state.
if (_inner == null) {
return VirtualChannel._(this, inputId, Stream.empty(), NullStreamSink());
}
late StreamChannelController<T> controller;
if (_pendingIds.remove(inputId)) {
// If we've already received messages for this channel, use the controller
// where those messages are buffered.
controller = _controllers[inputId]!;
} else if (_controllers.containsKey(inputId) ||
_closedIds.contains(inputId)) {
throw ArgumentError('A virtual channel with id $id already exists.');
} else {
controller = StreamChannelController(sync: true);
_controllers[inputId] = controller;
}
controller.local.stream.listen(
(message) => _inner!.sink.add(<Object?>[outputId, message]),
onDone: () => _closeChannel(inputId, outputId));
return VirtualChannel._(
this, outputId, controller.foreign.stream, controller.foreign.sink);
}