Kulwinder Singh
10/08/2019, 11:16 AMcallbackFlow
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)) }
}
}
}
Manuel Vivo
10/08/2019, 11:21 AMJob
to the liveData
builder and cancel it when neededKulwinder Singh
10/08/2019, 11:35 AMval appointmentJob = Job()
val myAppointments = _appointmentDate.switchMap {
appointmentJob.complete()
liveData(appointmentJob) { /.../ }
}
Kulwinder Singh
10/08/2019, 11:36 AM+ <http://Dispatcher.IO|Dispatcher.IO>
or other with Job
?Manuel Vivo
10/08/2019, 12:04 PMliveData
uses Dispatchers.Main
var appointmentJob: Job?
val myAppointments = _appointmentDate.switchMap { date ->
appointmentJob.cancelIfActive()
appointmentJob = Job()
liveData(appointmentJob) { /.../ }
...
}
fun Job?.cancelIfActive() {
if (this?.isActive == true) {
cancel()
}
}
Manuel Vivo
10/08/2019, 12:07 PMliveData
Kulwinder Singh
10/09/2019, 5:35 AMManuel Vivo
10/09/2019, 7:52 AM