*For an android developer, network layer building is a very basic thing. In recent years, I have been updating the network package, from the beginning of rxjava+retrofit, to the later livedata+retrofit, in the subsequent various packages, every time I rewrite, I feel that I wrote before like a ball of shit.
In the repeated rewrite work, accumulated a lot of experience, in this process, also to refer to the design of different projects.
In my spare time, I started rewriting again, this time using flow+rxjava*
上面说了一堆废话,咱们接入正文。
需求场景:随你。反正我是写着玩的
代码移植难度:低。
学习成本:低。
可用于学习flow+retrofit。
retrofit 构建部分 参考其他,网上太多了
我对于这部分的思考,主要集中在viewModel和Repository 这两部分
对于我来说viewModel中主要是对flow下游的处理,Repository主要做网络请求的封装
首先我们看看viewModel这部分代码
首先在这个viewModel中我们可以看到flow声明,其次我们能看到请求的方法,而方法里面就是后续的封装 另外我们看到了BaseAndroidViewModel这个父类,让我们看看具体的内容
可以看到这个viewModel集成了AndroidViewModel,至于为什么要继承这个而不是viewModel(),请看下上面的注释。在其中我们有两个委托,一个接下来要强的网络封装,另一个就是大家知道retrofit的Factory了
上面代码极其简单,大家看看就好
下面是就是具体的针对封装了
我贴出所有的拓展函数,上面有密封类,协程,flow这几项基础知识,如果有不明白的函数可以自己查一下,这样才能更好的学习。