orhanobut / effective-android

Effective android items
http://orhanobut.github.io/effective-android/
Apache License 2.0
79 stars 13 forks source link

Network Calls inside Fragments #6

Open safaorhan opened 6 years ago

safaorhan commented 6 years ago

Hi @orhanobut, I really liked effective-android project. Keep up the good work!

Today, one of my collagues asked why is it a bad practice to make a network call inside a fragment, referring to this project. I haven't thought about it much, until this day.

Why do you consider network calls in a fragment as a violation of Single Responsibility principle?

In my opinion, Fragments are different than Views or ViewGroups. They have their own lifecycle, state management, etc.

Also, when I searched android training docs, I found samples in which network calls are being handled in Fragments. (https://developer.android.com/training/basics/network-ops/connecting.html)

Can you elaborate please?

orhanobut commented 6 years ago

Hi @safaorhan

Long time I checked this repo, I should definitely update some of the items. Since then, a lot of different architectures are emerged, especially MVP and MVVM. There is no certain rule about this concern. Fragments can make network calls. I think it all depends how they are treated. But even for now, I would try to extract network calls to somewhere else, e.g. Repository pattern, which can handle all data related concerns and can transform data models to domain model. This would make it easier to test them, and also each part can be re-used in different places.

There are actually many articles about separation of concerns, one thing I always keep in my mind is that, nothing is written into stones and everything can change on different circumstances.