Skip to content

Instantly share code, notes, and snippets.

@scottroemeschke
Created October 29, 2017 17:29
Show Gist options
  • Save scottroemeschke/8752ea668cb713ffcae43430a7db6c7d to your computer and use it in GitHub Desktop.
Save scottroemeschke/8752ea668cb713ffcae43430a7db6c7d to your computer and use it in GitHub Desktop.
Example of combining observable<list<T> and a list field, where they merge together sharing an id, from reddit question
/*
using RxJava2, I'd like to "join" two lists.
I have a List<ObjectA> and List<ObjectB> whereas ObjectA (val id: String, val something: Int) and ObjectB(val id: String, val somethingElse: Boolean) and want to combine them to an ObjectC (val id: String, val something: Int, val somethingElse: Boolean but in such a way, where it will only join elements, if their ids are equal and all of that possibly in the most efficient way
think of an sql-join for this
Below is an example implementation:
should be noted depending on specifics this might be a very
wierd thing to do (some data is live and reactive, other potentially stale etc.)
also the runtime perfomance would vary depending on if these lists were ordered or not (and how many items)
if sorted, you could have a better algorithm
this implementation also assumes no duplicate ids, and that every id will have a match in each list
also these iterations will run every time there is a new list of type A (users in this example)
which is pretty expensive if this list is ACTUALLY observable and is updated often
*/
data class User(val id: String, val name: String)
data class UserRating(val id: String, val rating: Int)
data class UserWithRating(val id: String, val name: String, val rating: Int)
class Example(val users: Observable<List<User>>, val userRating: List<UserRating> {
fun merge(): Observable<UserWithRating> {
//this functions could be pulled out with names instead of all in-line if preferred
return users.map {
it.map {
user -> UserWithRating(id = user.id,
name = user.name,
rating = userRating.find { userRating -> userRating.id == user.id }!!.rating)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment