Chapter 8: Observable’s collection transformers operators

android2ee (Seguy Mathias)
2 min readJan 5, 2021

We will see the following operators on Observables:

  • toList
  • toSortedList
  • toMap
  • toMultiMap
  • collect

They help to transform the stream emitted in a collection, mainly list and map. For this chapter, we keep using the days of the week observable.

toList

Convert your emitted items into a list that is emitted when onComplete occurs. You can provide or not the expected list size.

toSortedList

Convert your emitted items into a list that is emitted when onComplete occurs. You can provide or not the expected list size.
You have to provide the comparator (or the default one will be used if it exists)

toMap

toMap help you having a map which is <key,Item> Convert your emitted items into a map that is emitted when onComplete occurs.
You can provide for each items only its key, the value will be the item itself.
You can ALSO provide for each items its key and its value
** /!\Important fact/!\ **
If an item has the same key as a previous item, the item will override the previous one in the map.
So your map is <key, item> where you have only on item for a key

toMultiMap

toMultiMap help you having a map which is <key,List < Item > >
Convert your emitted items into a map that is emitted when onComplete occurs.
You can provide for each items only its key, the value will be the item itself.
You can ALSO provide for each items its key and its value

** /!\Important fact/!\ **
If an item has the same key as a previous item, the item will be added in the list associated with this key.
So your map is <key,List < Item > > where you gather all the items with the same key in a list

Collect

collect is a more generic operator which let you manage exactly the collection and how to fill it.
You need to provide the constructor of your collection and the way to add your item in your collection.

So, we can use collect to code the toMultiMap operator and it’s a good example to understand the power of collect:

More on the topic

Previous chapter: Chapter 7: Observable transformers operators

Next chapter: Chapter 9: Observable’s action operators

This chapter is a small part of a biggest training project, you can find on Github. You’ll have the main branch with the answers/responses/unit tests and documentation. You could start with the “questions” branch to only have the questions.

You’ll have the full table of content of the articles on Medium.

You can download the book on Android2ee

Warning: Those articles has been created only because I am stuck in a Rx Android project and I need to prepare the ramp up for those who will replace me.

My conclusion : Choose Kotlin and suspending function instead of Rx. PLEASE, save your project from RxHell !!!

Write Medium in Markdown? Try Markdium!

--

--

android2ee (Seguy Mathias)

Android2ee alias Mathias Seguy. Android expert gives you some news on the Android world. mathias.seguy@android2ee.com