Issue
I have this use case GetPeopleUseCase which allows me to retrieve data (students and footballers) from cache. Now, I have to merge footballer and student in one list. How can i do it?
class GetPeopleUseCase @Inject constructor(
private val footballerRepository: FootballerRepository,
private val studentRepository: StudentRepository
) {
suspend fun execute(): Result<List<Person>> {
val footballer = footballerRepository.getFootballers()
val student = studentRepository.getStudents()
// How do I merge footballer and student?
}
}
Person:
abstract class Person
Footballer:
data class Footballer(
val name: String,
val code: String
) : Person()
Student:
data class Student(
val name: String,
val code: String
): Person()
Solution
I believe you can do something like this:
if (footballer.isSuccess && student.isSuccess) {
return Result.success(footballer.getOrThrow() + student.getOrThrow())
}
if (footballer.isSuccess) return footballer
return student
This way it combines them when both are success, or returns just one of them if they are success. And returns the student result if both were failed. If you want to return a failed result when either fail you could do
if (footballer.isSuccess && student.isSuccess) {
return Result.success(footballer.getOrThrow() + student.getOrThrow())
}
if (footballer.isFailure) return footballer
return student
Answered By - Ivo
Answer Checked By - David Marino (JavaFixing Volunteer)