1
votes

I have an Android app based on MVP + interactors + repositories. All layers from repository to presenter are wired using reactive streams (RxJava 2). View requests something from presenter, presenter asks from interactor, interactor asks from repository and repository asks from API itself. Response passes through the same layers as reactive stream from API to presenter. Each layer can map data for underlying layer.

The question is. Where should I call subscribeOn(io()/computation()/etc) and observeOn(AndroidSchedulers.mainThread()) ? I think that observeOn(AndroidSchedulers.mainThread()) should be called from presenter because heavy computings could be performed in interactor. In many examples subscribeOn(io()/computation()/etc) is called from presenter, but I don't agree with this approach. I think that presenter shouldn't decide in which thread to load data. Repository should decide in which thread to load data from API. For example if we have the repository interface to load contacts. An implementation can get data from DB or Internet or in-memory storage. There is no need to create thread for in-memory repository. So repository should decide whether subscribe on io/computation/etc scheduler or not.

Any ideas?

1
In my openion multithreading stuff are not related to model and logics. They might differ by platforms, so I set the schedulers of streams in the presentation layer.Mahdi-Malv
agree with @Malv its doesnt relate to architecture. Ususally i would subsbcribe in view and observe api responses in presenter.Andriy Tereshko

1 Answers

2
votes

I would not call subscribeOn() and observeOn() in the repository layer for the following reasons:

  • Methods that implicitly execute on different threads are very hard to use and may cause problems in the clients that are calling them.
  • If you want to compose multiple streams coming from different repositories, it would be more convenient to have control over them. If they are subscribed on different threads, this may lead to subtle bugs, less than optimal performance and hard to read code.
  • This adds another responsibility to the repo layer. Instead of being simple data stores, the repos are now aware of threads. In my opinion, this breaks the single responsibility principle.

I generally call subscribeOn() and observeOn() in the last layer before the views - in that case this will be your presenter layer. There I have full control over the composition of the interactors and better judgement over where I want to process things and where do I need the results of the processing.