Docs

PK battles: two live rooms in one

Put two hosts and both of their audiences together for a battle, then send everyone back to their own room. Flutter and React Native, with the beauty filter on.

How a PK works

Each host is live in their own room. For the battle, both hosts and their viewers move into one shared PK room: the two hosts see and hear each other, and every viewer sees both hosts. When the battle ends, everyone goes back to the room they came from. A user is in one room at a time, so there is no second connection to manage.

  1. Your server starts the PK

    It picks a PK room name and tells both hosts and their audiences.

  2. The hosts move

    Each host joins the PK room with a publishing token. Camera, microphone and beauty filter come along.

  3. The audiences follow

    Viewers switch to the PK room with a viewer token and see both hosts.

  4. Back home

    When the battle ends, everyone switches back to their own room the same way.

In our tests on two Android phones with the beauty filter on, a Flutter host was live in the PK room 1.6 to 2 seconds after the switch started and a React Native host 2 to 3 seconds; coming back home took up to 4 seconds. A web viewer switched rooms in about half a second.

1. Your server starts the PK

The invite, the accept, the scores and the gifts are your app's own logic. What Gravix needs is one room name per battle and tokens for it: your token endpoint signs the PK room with canPublish: true for the two hosts and false for viewers, exactly like any other room.

server/pk.js
// Your backend: when host A accepts host B's PK invite.
// The room name is yours to choose; one name per battle.
const pkRoom = `pk_${battleId}`;
// Tell both hosts and their audiences (your own realtime channel, push or polling):
notify(hostA.roomId, { type: 'pk_start', pkRoom });
notify(hostB.roomId, { type: 'pk_start', pkRoom });
// Your token endpoint signs pkRoom tokens: canPublish true for the two hosts, false for viewers
// (in a voice PK, also true for users on a seat). Check the user belongs to room A or B.
// Someone who opens room A or B during the battle: send them to pkRoom instead.
// When the battle ends: notify(..., { type: 'pk_end' }) and everyone goes home.

2. The hosts move

Both hosts run the same code. Fetch the PK room's token first, while still live at home, so the gap is only the leave and the join.

lib/pk_host.dart
import 'package:gravix_rtc/gravix_rtc.dart';

final room = GravixRoomService(videoEffect: GravixBeautyEffect(licenseToken: effectsToken));
final tokens = GravixTokenProvider.endpoint(Uri.parse('https://YOUR-BACKEND/rtc/token'));

// One call for every move: connect() leaves the current room first, then joins the new one.
Future<bool> enter(String roomId) async {
  // Token first, while still live in the old room: the gap is only leave + join.
  final c = await tokens.getCredentials(
      GravixTokenRequest(room: roomId, identity: userId, canPublish: true));
  final micOn = !room.isMicMuted.value; // a host who muted stays muted after the move
  return room.connect(url: c.url, token: c.token, publishMic: micOn, enableVideo: true);
}

await enter(myRoomId);                                  // live in my own room
await room.setVideoEffectParams({'look': 'glow', 'tone': {'smoothness': 0.6}}); // one call: kept across the moves

// pk_start: both hosts and their audiences move to the PK room.
await enter(pkRoom);
// pk_end: back home.
await enter(myRoomId);
pkHost.ts
import { AudioSession, GravixBeautyEffect, GravixRoomCamera, GravixTokenProvider, Room } from 'gravix-rtc-react-native';

const beauty = new GravixBeautyEffect({ licenseToken }); // one effect for every room
const tokens = GravixTokenProvider.endpoint('https://YOUR-BACKEND/rtc/token');
let current: { room: Room; camera: GravixRoomCamera } | null = null;

export async function enter(roomId: string) {
  // Token first, while still live in the old room: the gap is only leave + join.
  const { url, token } = await tokens.getCredentials({ room: roomId, identity: userId, canPublish: true });
  const micOn = current ? current.room.localParticipant.isMicrophoneEnabled : true; // keep a mute
  if (current) {
    await current.camera.dispose();
    await current.room.disconnect();
  }
  const room = new Room({ adaptiveStream: true, dynacast: true });
  const camera = new GravixRoomCamera(room, { videoEffect: beauty });
  await camera.connect(url, token);
  await room.localParticipant.setMicrophoneEnabled(micOn);
  await camera.setVideoEffectParams({ look: 'glow' }); // a new room camera starts without a look
  current = { room, camera };
  return room;
}

await AudioSession.startAudioSession(); // once, before the first room
await enter(myRoomId);   // live in my own room
await enter(pkRoom);     // pk_start
await enter(myRoomId);   // pk_end
// Going offline: current.camera.dispose(); current.room.disconnect(); AudioSession.stopAudioSession()
  • Flutter: GravixRoomService.connect with a token for another room leaves the current room first, then joins. The beauty look and sliders of the last setVideoEffectParams call carry over.
  • React Native: one GravixBeautyEffect serves every room; each room gets its own GravixRoomCamera. Set the look again after the move.

3. The audiences follow

lib/pk_viewer.dart
final room = GravixRoomService();
final tokens = GravixTokenProvider.endpoint(Uri.parse('https://YOUR-BACKEND/rtc/token'));

Future<bool> watch(String roomId) async {
  final c = await tokens.getCredentials(
      GravixTokenRequest(room: roomId, identity: userId, canPublish: false));
  return room.connect(url: c.url, token: c.token); // leaves the current room first
}

await watch(hostRoomId);  // watching the host
await watch(pkRoom);      // pk_start: both hosts on screen
await watch(hostRoomId);  // pk_end
pkViewer.ts
import { AudioSession, createGravixJoin, GravixTokenProvider } from 'gravix-rtc-react-native';

const join = createGravixJoin({
  tokenProvider: GravixTokenProvider.endpoint('https://YOUR-BACKEND/rtc/token'),
});
const viewer = (roomId: string) => ({ room: roomId, identity: userId, canPublish: false });

await AudioSession.startAudioSession();          // once, before the first room
let room = await join.attach(viewer(hostRoomId)); // watching the host

// pk_start: the old room is left and the PK room joined in one step.
join.switchTo(viewer(pkRoom));
room = await join.attach(viewer(pkRoom));         // read room.remoteParticipants, then listen

// pk_end
join.switchTo(viewer(hostRoomId));
room = await join.attach(viewer(hostRoomId));
// Closing the live screen: await join.leave(); await AudioSession.stopAudioSession();
  • Viewers join with canPublish: false: they watch and listen, and cannot be heard. To bring a viewer on stage, see roles and permissions.
  • React Native and web: switchTo stops the old room and connects the new one as soon as it closed. Events from before attach are not replayed, so read room.remoteParticipants right after it.

4. End the battle

When your server ends the battle, everyone calls the same function with their home room: hosts enter(myRoomId), viewers switch back to their host's room. Leaving the PK room needs nothing else. Fetch the home token as soon as the end message arrives, so the move back is only the leave and the join.

Mute the other host

A host or viewer who does not want to hear the other side can mute them on their own phone. Nobody else is affected, and the other host keeps talking to their own audience.

lib/pk_mute.dart
// "Mute the other host": only this phone stops hearing them. The PK room is not changed.
await room.muteRemoteAudio(opponentId, true);   // opponentId = the other host's identity
await room.muteRemoteAudio(opponentId, false);  // hear them again
// Applies to who is in the room now: call it again if the other host rejoins.
pkMute.ts
import { RoomEvent, type Room } from 'gravix-rtc-react-native';

// "Mute the other host": only this phone stops hearing them. The PK room is not changed.
export function muteOpponent(room: Room, opponentId: string, mute: boolean) {
  const apply = () => room.remoteParticipants.forEach((p) => {
    if (p.identity === opponentId) p.audioTrackPublications.forEach((pub) => pub.setSubscribed(!mute));
  });
  apply();
  room.on(RoomEvent.TrackPublished, apply); // also when the other host rejoins
  return () => room.off(RoomEvent.TrackPublished, apply);
}

To mute the other host for everyone, store the choice on your server and have every app in the PK room apply it.

Good to know

  • Viewers are faster than hosts: move the hosts first, or show a "PK starting" screen until both hosts' video arrives (a few seconds).
  • While a PK runs, the hosts' own rooms are empty. Send people who open a host's room during the battle to the PK room; your server knows which battle is on.
  • The PK room is only for sound and video. Chat, gifts and seats can stay on each host's own room in your app, so nothing has to move with the user.
  • Keep scores, timers and gift totals on your server, or send them to the room as data messages. They do not depend on which room a viewer is in.
  • A viewer who misses the switch message keeps watching an empty room. Have the app check the host's status with your server when the host's video ends.

Planning PK battles in your app?

Tell us about your live app and we will help you set up rooms, roles and the beauty filter.