i'm using this
callbackFlow
to listen updates of Firestore Collection using below extension function
@ExperimentalCoroutinesApi
fun Query.getQuerySnapshotFlow(): Flow<QuerySnapshot?> = callbackFlow {
val listenerRegistration = addSnapshotListener { querySnapshot, e ->
if (e != null) {
cancel(message = "", cause = e)
return@addSnapshotListener
}
offer(querySnapshot)
}
awaitClose {
listenerRegistration.remove()
}
}
@ExperimentalCoroutinesApi
fun <T> Query.getDataFlow(mapper: (QuerySnapshot?) -> T): Flow<T> {
return getQuerySnapshotFlow().map { mapper(it) }
}
and i'm using above extension functions like below inside my ViewModel, but how can i cancel previous
Flow
, which is started in
else
case below, because when
switchMap
is called again then it will keep listening old Collection and will start new one. how can i fix this?
val myAppointments = _appointmentDate.switchMap { date ->
//HERE I WANT TO CANCEL PREVIOUS FLOW STARTED IN ELSE CASE BELOW
liveData {
if (date == null)
emit(AppointmentState.NoAppointment)
else {
myCollection.whereEqualTo(Appointment.DATE, date)
.getDataFlow { it!!.toObjects<List<Appointment>>() }
.collect { emit(AppointmentState.Loaded(it)) }
}
}
}