Map operator Implementation Chapter 22

Greetings I was just wondering if the map operator placement matters in this case. Should it be after the subscribOn operator? Also, since we are using Live Data’s post value, there is no need to observeOn on the main thread correct?

Here is the code snippet
repository
.taskStream()
.map { tasks → tasks.map { TodoListItem.TaskListItem(it) } }
.map { listItems →
val finishedTasks = listItems.filter { it.task.isDone }
val todoTasks = listItems - finishedTasks
listOf(
TodoListItem.DueTasks,
*todoTasks.toTypedArray(),
TodoListItem.DoneTasks,
*finishedTasks.toTypedArray()
)
}
.subscribeOn(backgroundScheduler)
.subscribe(listItemsLiveData::postValue)
.addTo(disposables)”

Thank you,

Angel Rodriguez

Hey @alexsullivan. Apologies in advance and thank you for your time. if you could give me some input on this that would be awesome!

Thank you.

Hi @arrmixer,

The map placement definitely does matter. In this scenario it’s less important, but in general the order of operations matters both to figure out what type of data you’re operating on and to know what threading operators are being applied/where the code is being run. In this scenario, it’s not particularly important because there’s no potential race conditions and the work isn’t heavy enough to need to be of the mainthread - in general this placement should be fine.

And yes - we don’t need the result to be emitted on the main thread since we’re using postValue, so we don’t need a call to observeOn.

Does that answer your question?

1 Like

@alexsullivan
yes so if I understand correctly the map operator returns an observable and does its work after the original observable completed its work and both the map operator and the original observable will work on the same thread that I subscribeOn?

Or the map operator automatically works on the Main Thread? which if it does then now I understand why you say it doesn’t matter… because it’s basically a map operator like the one in Kotlin…
So, I don’t necessarily need to add the map operator after the subscribeOn correct?

sorry if I keep asking Im just trying wrap my head around the concept better.

@arrmixer Exactly!

Schedulers are some of the most confusing parts of RxJava, so don’t worry if it doesn’t seem super clear at first.

subscribeOn will, broadly speaking, change the thread your code is running on in operators called above the call to subscribeOn. Now, that’s actually an oversimplification depending on how you use multiple calls to subscrobeOn or observeOn but it gets the general sentiment across.

So in your example, all of your rx operators are being run on your backgroundScheduler. If you had an observeOn operator after, say, the first map, then the second map and subsequent operators would be run on whatever Scheduler you passed in to observeOn

Make sense?

1 Like

yes, @alexsullivan thank you brother much appreciated! :muscle: :smiley: