SupabaseS
Supabase2y ago
Tobs

Disconnecting and reconnecting from realtime channels

I have a realtime table that i am listening to inserts and updates from with this getStream function.

suspend fun getStream(gameId: String?): Flow<StreamSupabase> {
        val channel = createChannel(gameId)
        val channelFilter ="is_featured=eq.true"
        
        val changeFlow = channel.postgresChangeFlow<PostgresAction>("public") {
            table = "Stream"
            filter = channelFilter
        }.map {
            when (it) {
                is PostgresAction.Delete -> error("Delete should not be possible")
                is PostgresAction.Insert -> it.decodeRecord<StreamDto>().mapToEntity()
                is PostgresAction.Select -> error("Select should not be possible")
                is PostgresAction.Update -> it.decodeRecord<StreamDto>().mapToEntity()
            }
        }.catch {
            Log.d("StreamDatasource", "getFeaturedStream Error: $it")
        }
        channel.subscribe()
        return changeFlow
    }

This works great. However it only works the first time that the page is being loaded. I connect to the stream using LaunchedEffect, and i have tested that the getStream function is called when i return to the page.

I get no events after i return to the page, even though i can listen to the same channel on the supabase website, and events are happening there. Do i have do disconnect from the channel in a specific way or do i have to do something different when i reconnect?

I tried removing the channel with a DisposableEffect like so:
DisposableEffect(null){
        onDispose {
            streamViewModel.stopListening(null)
        }
    }


suspend fun stopListening(gameId: String?) {
        val channel = createChannel(gameId)
        supabaseClient.realtime.removeChannel(channel)
    }

Any ideas?
Was this page helpful?