How to use Flows with Socket.io in Android?

Viewed 372

On the server side, I have a WebSocket which emits the "Session Object" frequently to its clients.

const session = {
  ...
}
io.emit("session_obj", session)

Now, on the Android side, I want to collect this session object in a FlowBuilder and emit the session object to its collectors in the ViewModels.

class MainRepositoryImpl @Inject constructor(
  socket: Socket
) : MainRepository {
  override fun getRealtimeSessionObject(): Flow<Command> {
    /*
     * socket.on("session_obj") {
     *     val session = it[0] as JSONObject
     * }
     */
    // But how will I return as a flow that can emit the data to ViewModels?
  }
}
1 Answers

You can use SharedFlow to emit data to ViewModel, it is a hot stream of data. Example of usage:

private val dataFlow = MutableSharedFlow<Command>(extraBufferCapacity = 128)

fun getRealtimeSessionObject(): Flow<Command> {
    socket.on("session_obj") {
        val session = it[0] as JSONObject
        // ...
        dataFlow.tryEmit(command)
    }
    return dataFlow
}

extraBufferCapacity - the number of values buffered.

Related