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.
Billy Newman
06/26/2023, 1:43 PM
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?
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
Sam
06/26/2023, 1:51 PM
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
Billy Newman
06/26/2023, 1:52 PM
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!