Can anyone shed some light on why the `asFlow`exte...
# squarelibraries
k
Can anyone shed some light on why the `asFlow`extension for SQLDelite is written using a channel? I understand how it works, but I feel like I'm missing the reasoning for why we need a channel.
Copy code
fun <T : Any> Query<T>.asFlow(): Flow<Query<T>> = flow {
  val channel = Channel<Unit>(CONFLATED)
  val listener = object : Query.Listener {
    override fun queryResultsChanged() {
      channel.offer(Unit)
    }
  }
  addListener(listener)
  try {
    emit(this@asFlow)
    for (item in channel) {
      emit(this@asFlow)
    }
  } finally {
    removeListener(listener)
  }
}


// why do we need the Channel?
fun <T : Any> Query.asFlow(): Flow<Query<T>> = flow {
  val listener = object : Query.Listener {
    override fun queryResultsChanges() {
      emit(this@asFlow)
    }
  }

  addListener(listener)
  try {
    emit(this@asFlow)
  } finally {
    removeListener(listener)
  }
}
d
Changes happen whether we listen to them or not, which makes them hot. Flows represent cold streams so they cannot not be fed data directly. So here we feed the hot data to a channel (which is a hot representation) and then use a flow to coldly read from it.
👍 1
🚫 1