I'm trying to de-dupelicate some Flow code. I basi...
# getting-started
c
I'm trying to de-dupelicate some Flow code. I basically have this method repeated pretty much identically for a bunch of different firestore queries. Is there a way to wrap this up so I don't have to do all of this cermoney for each firestore query I write?
Copy code
fun getBooks(): Flow<List<Book>> {
  return callbackFlow {
    val listener =
      FirebaseFirestore.getInstance().collection("books").addSnapshotListener { value, error -> trySend(value to error) }
    awaitClose { listener.remove() }
  }
  .doSomethingWithNullValueAndError()
  .conflate()
  .map { (value, _) -> 
    value.toObjects()
  }
  .flowOn(defaultDispatcher)
In an ideal api (i think) i'd be able to write something like this
Copy code
fun getBooks(): Flow<List<Book>> {
val query = FirebaseFirestore.getInstance().collection("books")
return getFirestoreFlowable(query, Book.class::java)
}
and
Copy code
fun getPeople(): Flow<List<Person>> {
val query = FirebaseFirestore.getInstance().collection("person").        .whereEqualTo("person.visibility", true)
return getFirestoreFlowable(query, Person.class::java)
}
and then I'd have a generic
Copy code
fun <T> getFirestoreFlowable(query: Query, type: T): Flow<T> {
  return callbackFlow {
    val listener =
      query.addSnapshotListener { value, error -> trySend(value to error) }
    awaitClose { listener.remove() }
  }
  .doSomethingWithNullValueAndError()
  .conflate()
  .map { (value, _) -> 
    value.toObjects()
  }
  .flowOn(defaultDispatcher)
Does that sound or look alright?
j
What is
doSomethingWithNullValueAndError()
? If you're throwing on errors, why not just do it with the
close(Throwable)
from inside the
callbackFlow
? Also, I'd rather declare such functions as extensions, for instance an extension function on
Query
here
Another question, where do you use
type
here?
c
I just got
doSomethingWithNullValueAndError()
from a snippet that @uli was helping me with. An exntention function on query makes sense here to me. Where do I use type... Hm. I need it for the
value.toObjects()
so that it knows what type to return