Hello all, wondering if someone can help with an i...
# getting-started
b
Hello all, wondering if someone can help with an issue I am having combining multiple flows. I am trying to merge multiple flows into one flow, the elements in the flow are of a super class. When I collect the flow I am only ever seeing elements from one of the flows. Code in comments.
Copy code
open class Person()
class Student(): Person()
class Teacher(): Person()
DB queries:
Copy code
@Query("SELECT * from students WHERE important = 1")
fun observeStudents(): Flow<List<Person>>

@Query("SELECT * from teachers WHERE important = 1")
fun observeTeachers(): Flow<List<Person>>
Merge the flows:
Copy code
fun observeImportantPeople(): Flow<List<Person>> {
   val students = studentDao.observeStudents()
   val teachers = teacherDao.observeTeachers()
   return merge(students, teachers)
}
With 2 students and one teacher, I will see either 2 students in the flow list or 1 teacher in the flow list. Any ides?
s
If you want one list containing the latest students and the latest teachers, you can use `combine`: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/combine.html
b
Thanks Sam, unfortunately when using combine I get a compile time error:
Copy code
Type mismatch.
Required:
Iterable<Flow<TypeVariable(T)>>
Found:
Flow<List<Person>>
s
What does your code look like? I think it should be something like this:
Copy code
fun observeImportantPeople(): Flow<List<Person>> {
   val students = studentDao.observeStudents()
   val teachers = teacherDao.observeTeachers()
   return combine(students, teachers) { s, t -> s + t }
}
b
Ah, was just using
Copy code
combine(students, teachers)
Didn’t realize you have to provide a function specifying how to combine the lists Thank you!
👍 1
🍻 1
🐕 1