android - 我不想在V层的抽象里请求网络,有什么办法吗?
PHPz
PHPz 2017-04-18 09:18:47
0
3
773

感谢您查看我的疑问.

我有个很多个fragment(我的V层)
他们里面都有请求网络的操作,他们通常只会关心请求成功的数据

所以我就抽取了一个BaseFragment 在这个BaseFragment 里面,将请求网络时的进度显示,失败处理 做了统一处理,那么在他的子类中就只需要关心请求成功后的数据了.

但是我发现这样做的话,代码量的确是下降了很多,请求网络的时候我的fragment 也只需要调用父类的类似requestData(String request) 的方法,传入对应的request就可以在类似onRequest(JavaBean bean) 中获得需要的对象了.

但是这样做的话,我总感觉有哪里不对,不清楚是不是因为我把请求网络直接放在了BaseFragment里面,如果这样的话,我再设计一个请求网络的util 类,每次请求的时候需要将BaseFragment 的引用(this)传入,然后在util 中的合适的位置对BaseFragment 的实例进行操作.把请求网络的抽象都放在util 中,共性直接就可以在util 中完成.

但是这样做也只是多了一个类,这个util 只为BaseFragment 服务,基本和原本没什么区别.所以我认为我的代码还是有很大问题的.

顺便问一下,如果是MVP 架构的话,是怎么在P层调用M层请求网络数据的时候,处理V进度失败的呢? 每次请求网络都要带着V层引用传递过去?如果这样做的话代码写起来不是非常难看?如果不传递过去,那么比如失败处理不是每次请求都需要在失败的位置又从P 层通知V层? 如果是小项目的话原本可能300~500行的代码,这样做的话可能就要多3~5 类,代码也要多好多了.

不知道我的想法是不是有很严重的误区

  1. 我的每个页面逻辑都很简单300~500 行代码就可以搞定了,所以根本不想用MVP

  2. 请求网络的逻辑我不想放在抽象(V层抽象)里面

  3. 对于统一的错误处理,又需要在抽象里面解决,不然每个子类都需要自己再实现完全一样的对错误的处理,代码重复

感谢您查看我的疑问.

PHPz
PHPz

学习是最好的投资!

reply all(3)
伊谢尔伦

I took over a project before, and the code was encapsulated like this. Later, due to the demand for the new version of the product, the original code could not be used at all. In desperation, I could only refactor.

  1. Why do we need to encapsulate network calls into BaseFragment? With such encapsulation, can we still clearly distinguish which call the returned data is generated from? If there are business needs that need to be distinguished, it will be very troublesome. e.g. Cancel a certain network call

  2. Besides, if you want to use Retrofit someday, what should you do?

  3. There are too many disadvantages to encapsulation like this. If you need network calls, just call them directly...

p.s. Activity/FragmentIs it the V layer? Isn’t it the C layer?

Reference:

  • MVC, MVP, MVVM in Android

  • What is the role of the Activity class in MVC?

伊谢尔伦

Now that you have encapsulated the network request, use it directly. Don’t cause trouble in subsequent debugging because of the convenience of the diagram. The benefits of modular layering are obvious. If you want to handle the same processing in BaseFragment, then I recommend an idea. See the following project for details:
sealtalk
You should focus on its network calling path, which is given in the UML diagram. It implements the use BaseActivity performs network requests. Of course, the request code is encapsulated in other files, and common errors are handled uniformly. You can refer to it below. Let’s focus on several files mentioned in UML.

Ty80

Encapsulate the interface and add an entity class Api, including a url and name
Use Api as parameters for each request and return
Use Api to distinguish which request is in the unified request callback

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template