sergdort / CleanArchitectureRxSwift

Example of Clean Architecture of iOS app using RxSwift
MIT License
3.9k stars 496 forks source link

[Question] What is the intent between using either subscribeOn or observeOn? #8

Closed lizhiquan closed 7 years ago

lizhiquan commented 7 years ago

Hi,

As I mentioned in the title, what is the difference between two use cases? observeOn: https://github.com/sergdort/CleanArchitectureRxSwift/blob/master/Network/Network/Network.swift subscribeOn: https://github.com/sergdort/CleanArchitectureRxSwift/blob/master/RealmPlatform/Repository/Repository.swift

Thank you. Your example is very great and it helps me a lot :)

sergdort commented 7 years ago

Hi, @lizhiquan! Glad that it helps :)

With subscribeOn you can specify on which scheduler (thread, queue) you want subscription to happened. And sometimes it's very important, for example in case of core data all operations need to be performed inside of the context.execute { } block. That's why I've used ContextScheduler there. In case of Realm I did not want all operations to be performed on the main thread as well

With observeOn you can specify on which scheduler (thread, queue) you want to observe values emitted by the observable sequence. And and it's very important when it comes to UI bindings because all UI related updates must be on the Main queue

lizhiquan commented 7 years ago

Hi, @sergdort! I understand the difference between two operators, but I wonder why don't you use subscribeOn in your Network requests. As I know, the code after observeOn will run on the scheduler you specified. So in this case, network request will run on current scheduler (maybe main scheduler) and the mapper to json will run on concurrent scheduler. If we use subscribeOn, we will make both api request and json mapper stuff all run on concurrent scheduler, which is more appropriate.

sergdort commented 7 years ago

In my opinion subscribeOn does not make any difference here as URLSession uses it's own internal queue to process response, and creating network request is not that performance impact operation ¯_(ツ)_/¯

lizhiquan commented 7 years ago

Thank you :)