How does room switching using livekit server roomS...
# ask-ai
p
How does room switching using livekit server roomService.moveParticipant work, I call that function for a particular user, but their tracks don't get republished again automatically, is that intended or do I need to do something for them to republish their tracks?
t
Thanks for reaching out, Daksh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi there! I wanted to share a bit about how the
roomService.moveParticipant
method in LiveKit works. When you move a participant from one room to another, their tracks are unpublished from the original room, and they won’t be automatically republished in the new room. This is actually how it’s designed to work. To make sure the participant’s tracks show up in the new room, you’ll just need to manually handle republishing the tracks from your client-side application once the participant has joined the destination room. If you need any help with that, I’m here for you! Sources: roomclient.go | pkg/rtc/participant.go | Connecting to LiveKit | LiveKit Docs | packages/livekit-server-sdk/src/RoomServiceClient.ts | livekit/livekit_room.twirp.go
p
also, what would be a better approach towards breakout rooms, shifting people to different rooms, or choosing who is subscribed to who
t
When it comes to setting up breakout rooms in LiveKit, a great way to do this is by using the
MoveParticipant
API to move participants between different rooms. This approach helps keep groups nicely separated, manages room lifecycles automatically, and handles signaling smoothly—so participants get the natural join and leave events in their respective rooms. While you might consider using subscription controls like
UpdateSubscriptions
to manage who hears which tracks, this method isn’t really designed for breakout rooms. It can make things more complicated and doesn’t offer the same clear separation or experience as using distinct rooms. So, for a clean and effective way to create breakout sessions, using the
MoveParticipant
API is definitely the way to go. Sources: Subscribing to tracks | LiveKit Docs | Rooms, participants, and tracks | LiveKit Docs | livekit/livekit_rtc.pb.go | livekit-api/livekit/api/room_service.py
p
does livekit offer a way to kick everyone out after some time has been elapsed?
t
Thank you for reaching out! I’d love to help clarify how LiveKit handles room disconnections. Currently, LiveKit doesn’t automatically disconnect all participants after a fixed time from when the room is created, regardless of activity. But don’t worry, there are two handy ways the system manages automatic room closure based on inactivity: • Empty Timeout: If no one joins the room within a certain period (which you can set using
empty_timeout
), the room will close automatically. • Departure Timeout: Once the last participant leaves, the room stays open for a bit longer (configured with
departure_timeout
). If no one comes back during this time, the room closes. If you’re looking to have a session that strictly lasts for a set amount of time—like 60 minutes from when the room is created—you can use the
DeleteRoom
API to close the room and disconnect everyone manually. You might find it helpful to set up a timer or a cron job in your app to handle this smoothly. Sources: pkg/rtc/room.go | Connecting to LiveKit | LiveKit Docs | Managing rooms | LiveKit Docs | protobufs/livekit_room.proto
p
can you give me a template for typescript for switching a room, how to handle on(Moved event
t
I'd love to share a helpful TypeScript template for handling room switching in LiveKit, including how to gracefully manage the
RoomEvent.Moved
event:
Copy code
`import { Room, RoomEvent, ConnectionState } from 'livekit-client';

class RoomSwitchManager {
  private currentRoom: Room | null = null;

  async connectToRoom(url: string, token: string): Promise<void> {
    const room = new Room();
    this.setupRoomEventListeners(room);
    await room.connect(url, token);
    this.currentRoom = room;
    console.log(`Connected to room: ${room.name}`);
  }

  private setupRoomEventListeners(room: Room): void {
    room.on(RoomEvent.Moved, this.handleRoomMoved.bind(this));
    room.on(RoomEvent.ConnectionStateChanged, (state: ConnectionState) => {
      console.log(`Connection state changed: ${state}`);
    });
  }

  private async handleRoomMoved(newRoomName: string): Promise<void> {
    console.log(`Moved to new room: ${newRoomName}`);
    // This is a great spot to update your UI, clear any previous state, or notify other parts of your application
  }

  async disconnect(): Promise<void> {
    if (this.currentRoom) {
      await this.currentRoom.disconnect();
      this.currentRoom = null;
    }
  }
}

// Usage example
const manager = new RoomSwitchManager();
manager.connectToRoom(&#39;wss://your-livekit-server&#39;, &#39;your-access-token&#39;);</code></pre><br/><p>This template thoughtfully includes:</p><ul><li>Event listener setup for <code>RoomEvent.Moved</code> to smoothly handle room switching.</li><li>Connection state management along with hooks for room-specific logic.</li><li>Methods designed to help you update the UI or clear state right after switching rooms.</li></ul><br/><p>If you have any questions or would like me to walk you through adding more features, just let me know—I’m here to help!</p>`
Sources: src/room/Room.ts
p
if I'm using server side move, I don't need to manually reconnect
t
You're absolutely right! When you use the server-side
MoveParticipant
API, the LiveKit SDK takes care of the reconnection process for the participant automatically. This means the participant is smoothly moved to the new room without any need for manual reconnection on the client side. Of course, you can still listen for the
RoomEvent.Moved
event to update your application logic, like refreshing the UI or clearing any room-specific data, but rest assured, no manual reconnection is necessary. If you have any questions about this, feel free to ask—I'm here to help!
p
after switching using MoveParticipant, how do I make sure my camera and audio state remains the same as previous room
t
I understand it can be a bit tricky when using
MoveParticipant
, as the camera and audio states (like whether they're enabled or disabled, and their settings) don’t carry over automatically because the participant’s tracks get unpublished during the move. But don’t worry, you can manage this smoothly by handling these states manually on your side: 1. Before you move, it’s a good idea to save the current camera and microphone states using
localParticipant.isCameraEnabled
and
localParticipant.isMicrophoneEnabled
. 2. Once the move is done, simply re-enable the camera and microphone in the new room with
setCameraEnabled(true)
and
setMicrophoneEnabled(true)
. 3. If you had specific track settings like resolution or frame rate, just reapply those using
setTrackSettings
or by republishing tracks with the settings you want. This way, you can make sure your participant’s media state stays consistent and everything feels seamless across rooms. If you need any help with this, I’m here for you! Sources: livekit/livekit_room.pb.go | pkg/rtc/participant.go | React Core and Components | roomclient.go
p
const lastRoomNameRef = useRef<string>(room?.name || '') const isRepublishingRef = useRef(false) useEffect(() => { if (!room || !localParticipant) return const handleRoomMoved = async (_name_: string) => { // Only process if room actually changed if (lastRoomNameRef.current === name || isRepublishingRef.current) { console.log('Room name unchanged or already republishing, skipping') return } isRepublishingRef.current = true lastRoomNameRef.current = name console.log(
You have been moved to room: ${name}
) try { // Wait a bit for the room switch to complete await new Promise(resolve => setTimeout(resolve, 500)) // Get current track states const videoPublication = Array.from(localParticipant.videoTrackPublications.values())[0] const audioPublication = Array.from(localParticipant.audioTrackPublications.values())[0] const videoTrack = videoPublication?.track as LocalVideoTrack | undefined const audioTrack = audioPublication?.track as LocalAudioTrack | undefined const wasVideoEnabled = videoTrack && !videoTrack.isMuted const wasAudioEnabled = audioTrack && !audioTrack.isMuted console.log('Track states before republish:', { wasVideoEnabled, wasAudioEnabled }) // Method 1: Unpublish and republish const republishPromises: Promise<any>[] = [] if (videoTrack) { console.log('Unpublishing and republishing video track') republishPromises.push( localParticipant.unpublishTrack(videoTrack) .then(() => new Promise(resolve => setTimeout(resolve, 200))) .then(() => localParticipant.publishTrack(videoTrack, { name: 'camera', simulcast: true, })) .then(() => { if (!wasVideoEnabled) { return videoTrack.mute() } }) ) } if (audioTrack) { console.log('Unpublishing and republishing audio track') republishPromises.push( localParticipant.unpublishTrack(audioTrack) .then(() => new Promise(resolve => setTimeout(resolve, 200))) .then(() => localParticipant.publishTrack(audioTrack, { name: 'microphone', })) .then(() => { if (!wasAudioEnabled) { return audioTrack.mute() } }) ) } await Promise.all(republishPromises) console.log('All tracks republished successfully after room move') } catch (err) { console.error('[MeetingUI] failed to republish tracks after move', err) } finally { setTimeout(() => { isRepublishingRef.current = false }, 1000) } } room.on(RoomEvent.Moved, handleRoomMoved) return () => { room.off(RoomEvent.Moved, handleRoomMoved) } }, [room, localParticipant]) Why is this not working, my video appears as blank to other participants
t
I'm sorry to hear that you're experiencing the video appearing blank after republishing tracks. This can sometimes happen due to missing negotiation or how the track states are handled. Let me guide you through some steps that usually help resolve this: 1. Trigger Negotiation: After you call
publishTrack
, make sure to explicitly trigger negotiation by using
localParticipant.engine.negotiate()
. This step is important to keep everything in sync. 2. Use Built-in Methods: Instead of manually unpublishing and republishing tracks, try using
republishAllTracks()
. This method handles the process smoothly and keeps everything synchronized. 3. Ensure Track Validity: Before republishing, double-check that the track isn't muted and that its state is live (for example,
track.mediaStreamTrack.readyState === 'live'
). 4. Retain Video Renderer: Make sure the video rendering component stays attached during the republish cycle. If needed, reattach it explicitly to avoid losing the video display. 5. Handle Reconnection Events: Keep an eye on
Reconnected
and
LocalTrackPublished
events. Listening to these helps confirm that media is flowing properly after any reconnection. Following these steps should help ensure your video and audio tracks are republished correctly and visible to everyone involved. If you need any further assistance, please don't hesitate to reach out—I'm here to help! Sources: livekit-android-sdk/src/main/java/io/livekit/android/room/participant/Local... | Connecting to LiveKit | LiveKit Docs | src/room/participant/LocalParticipant.ts | localparticipant.go | livekit/src/room/mod.rs
p
whenever I switch my room, unpublish my video and then republish it, then also others are not able to see my video
t
I'm sorry to hear that your video isn't showing up for other participants after unpublishing and republishing during a room switch. Let's work through some key steps together to help resolve this: 1. Trigger Negotiation: After you republish a track, make sure to explicitly trigger negotiation by calling
localParticipant.engine.negotiate()
. This helps signal the new track to everyone else in the room. 2. Handle Full Reconnection: If you experience a full reconnection, patiently wait for the
Reconnected
event, then ensure all your tracks are republished using
republishAllTracks()
. This keeps everything in sync. 3. Check Track State: It’s a good idea to verify that your track isn’t muted and that its state is live before republishing. For instance, check if
track.mediaStreamTrack.readyState === 'live'
to confirm. 4. Use Built-in Methods: Whenever possible, try to use
republishAllTracks()
instead of manually unpublishing and republishing tracks. This can help avoid any tricky synchronization issues. 5. Retry Logic: Sometimes, the first republish attempt might not go through. Implementing retry logic with backoff can be really helpful. If needed, you might also stop and recreate the track before trying again. I hope these steps make things clearer and help get your video visible to everyone after switching rooms. If you’d like, I’m here to walk you through specific code examples or any other questions you have! Sources: CHANGELOG.md | Connecting to LiveKit | LiveKit Docs | livekit-android-sdk/src/main/java/io/livekit/android/room/participant/Local...