============================
- 原文链接 : Flux Architecture on Android
Finding a good architecture for Android applications is not easy. Google seems to not care much about it, so there is no official recommendation on patterns beyond Activities lifecycle management.
找到一个好的应用架构对于Android来说并非易事,Goodle似乎并不那么关心这方面,因为他们并没有推荐一个合适的应用架构。
But defining an architecture for your application is important. Like it or not, every application is going to have an architecture. So you'd better be the one defining it than let it just emerge.
但是对于应用来说一个良好的架构是非常重要的。不管你是否同意,每个应用都应该有一个架构。因此,你最好为你的应用设计一个架构,而不是任由它发展。
=========================
Current trend is to adapt Clean Architecture, a 2012 Uncle Bob proposal for web applications.
现在比较流行的架构是Bob大叔在2012年发表的、针对于Web应用的清晰的软件架构。
I find Clean Architecture a little bit over-engineered for most of the Android apps out there.
但是我发现这个清晰的软件架构对于Android应用来说太过重量级了。
Typically mobile apps live shorter than web apps. Mobile technology is evolving so fast that any app released today is going to be completely deprecated in twelve months.
通常来说,移动应用都比web应用要简单。移动技术变化得很快,以至于今天发布的应用可能在一年之后就过时了。
Mobile apps usually do very little. A very high percent of use cases are just for data consuming. Get data from API, show data to user. Lot of reads, very little writes.
移动应用通常比较简单,比较多的使用场景只是对数据的处理。从API获取数据、向用户展示数据。更多的是阅读,很少有写内容的需求。
As a result its business logic is not complex. At least not as complex as backend apps. Well you have to deal with platform issues: memory, storage, pause, resume, network, location, etc. But that is not your app business logic. You have all of that in every app.
这也使得移动应用的业务逻辑不会太过于复杂
,至少不会比后端的应用复杂。当然,你也需要处理一些移动平台的问题:内存,存储,暂停,重新运行,网络,地理位置等等。但是这些并不是你的业务逻辑。
So it seems that most of the apps out there will not benefit from things like complex layer divisions or job priority execution queues.
因此,对于大多数应用来说并不会从复杂的分层架构或者具有优先级的任务队列中获得太多益处。
They may just need a simple way to organise code, work together efficiently and find bugs easily.
它们可能只是需要简单的方式来组织代码,使得各部分组件之间高效的一起工作,并且容易查找bug。
=============================
Flux Architecture is used by Facebook to build their client- side web applications. Like Clean Architecture it is not intended for mobile apps, but its features and simplicity will allow us to adapt it very well to Android projects.
Flux应用架构被facebook用于架构客户端Web应用,与Clean Architecture类似它也不是针对于移动应用的,它更简洁性能够让我们很方面的适用于Android应用。
There are two key features to understand Flux:
有两个关键特性能够帮助我们理解Flux :
The data flow is always unidirectional.
An unidirectional data flow is the core of the Flux architecture and is what makes it so easy to learn. It also provides great advantages when testing the application as discussed below.
数据流总是单向的 一个 单向数据流是Flux 应用架构的核心,这也使得它很容易学习。当你需要测试应用时它也提供了很便利的条件。
The application is divided into three main parts:
应用分为三部分 :
This three parts communicate through Actions: Simple plain objects, identified by a type, containing the data related to that action.
这三部分通过Action交互,Action是通过type标识的简单对象,它包含了一些与action相关的数据。
=========================
The main target of using Flux principles on Android development is to build an architecture with a good balance between simplicity and ease of scale and test. 在Android开发中使用Flux原则的主要目标就是创建一个简单、可伸缩、易于测试的应用架构。
First step is to map Flux elements with Android app components.
第一步需要做的就是在Android组件之间建立Flux元素的关系映射。
Two of this elements are very easy to figure out and implement.
这两类元素非常容易实现 :
View: Activity or Fragment
Dispatcher: An event bus. I will use Otto in my examples but any other implementation should be fine.
View: Activity 或 Fragment;
Dispatcher: 一个事件总线,我在示例中使用了Otto,但是其他实现也是可以考虑的,例如AndroidEventBus。
Actions are not complex either. They will be implemented as simple POJOs with two main attributes:
Action也不复杂,它们通常是一些含有如下两个主要属性的简单的对象:
Type: a String
identifying the type of event.
Data: a Map
with the payload for this action.
Type : 标识事件类型的一个String字段;
Data : 一个含有该Action信息的map字段。
For example, a typical action to show some User details will look like this:
例如,一个显示一些用户详细的action大致如下所示 :
Bundle data = new Bundle();
data.put("USER_ID", id);
Action action = new ViewAction("SHOW_USER", data);
This is perhaps the most difficult to get Flux concept.
Stores应该是Flux概念里最难理解的了。
Also if you have worked with Clean Architecture before it also will be uncomfortable to accept, because Stores will assume responsibilities that were previously separated into different layers.
如果你以前使用过Clean Architecture,你会感觉它也不是那么容易理解,因为Stores会假设职责已经被分割到不同的层。
Stores contain the status of the application and its business logic. They are similar to rich data models but they can manage the status of various objects, not just one.
Stores包含了应用的状态以及业务逻辑,它们很像功能完备的数据模型,但它们能够管理各种对象的状态,而不仅仅是其中一个。
Stores react to Actions emitted by the Dispatcher, execute business logic and emit a change event as result.
Stores对Dispatcher发出的Action做出响应,执行业务逻辑,处理完成之后发出一个change事件。
Stores only output is this single event: change. Any other component interested in a Store internal status must listen to this event and use it to get the data it needs.
Stores只会输出一个change事件,任何对一个Store的内部状态感兴趣的组件都需要监听该事件,并且使用它来获取数据。
No other component of the system should need to know anything about the status of the application.
系统中的其他部分并不需要了解应用的状态。
Finally, stores must expose an interface to obtain application Status. This way, view elements can query the Stores and update application UI in response.
最终,Store必须暴露一个接口来获取应用状态.这样一来,View元素就能够查询Store的状态以及更新UI。
For example, in a Pub Discovery App a SearchStore will be used to keep track of searched item, search results and the history of past searches. In the same application a ReviewedStore will contain a list of reviewed pubs and the necessary logic to, for example, sort by review.
例如,在一个酒吧查找App中,SearchStore被用于追踪搜索到的酒吧、搜索结果和经过的酒吧历史数据。另一个ReviewedStore包含查看过的酒吧列表以及必须的逻辑,例如排序。
However there is one important concept to keep in mind: Stores are not Repositories. Their responsibility is not to get data from an external source (API or DB) but only keep track of data provided by actions.
然后,有有一个重要的概念你必须要记住 : Store不是Repositories。它们的职责不是从外部资源(API或者数据库)中获取数据,只是追中action提供的数据。
So how Flux application obtain data?
那么Flux如何获取数据呢 ?
In the initial Flux graph I intentionally skipped one part: network calls. Next graph completes first one adding more details:
在前面的Flux图表中我特意省略了一部分: 网络调用。下一个图表将会完善这部分细节。
Asynchronous network calls are triggered from an Actions Creator. A Network Adapter makes the asynchronous call to the corresponding API and returns the result to the Actions Creator.
异步网络调用会从Actions Creator触发,一个网络适配器会触发一个异步的网络调用并且将结果返回到Actions Creator中。
Finally the Actions Creator dispatch the corresponding typed Action with returned data.
最终Actions Creator将含有相应type与数据的Action分发出去。
Having all the network and asynchronous work out of the Stores has has two main advantages:
所有的网络请求和异步操作从Store中隔离出来有两个优点 :
Your Stores are completely synchronous: This makes the logic inside a Store very easy to follow. Bugs will be much easier to trace. And since all state changes will be synchronous testing a Store becomes an easy job: launch actions and assert expected final state.
Store中的操作都是是完全同步的 : 这使得Store中的业务逻辑非常简单,bug也易于发现。并且,自从"所有的状态变化都必须是同步的"的运用到实际中,测试Store变得非常容易,只需要加载action,然后对最终的状态做一个断言判断;
All actions are triggered from an Action Creator: Having a single point at which you create and launch all user actions greatly simplifies finding errors. Forget about digging into classes to find out where an action is originated. Everything starts here. And because asynchronous calls occur before, everything that comes out of ActionCreator is synchronous. This is a huge win that significantly improves traceability and testability of the code.
所有Action都是从Action Creator被触发 : 从一个统一的点创建和启动所有用户的action使得查找错误变得很简单。省去了在各种Class之间查找该action的发出点,所有的action都出自Action Creator。因为异步调用在action发出之前已经调用,因此其他ActionCreator的函数都是同步的,这很大程度上提升了代码的可追踪性和可测试性。
===========================
In this example you will find a classical To-Do App implemented on Android using a Flux Architecture.
这个例子是按照Flux架构实现的To-Do Android应用。
I tried to keep the project as simple as possible just to show how this architecture can produce very well organised apps.
我尝试着尽量简单的演示如何使用Flux架构来构建一个组织良好的应用。
Some comments about implementation:
关于这个实现的一些解释 :
The Dispatcher
is implemented using Otto Bus. Any bus
implementation will mostly work. There is a Flux restriction on
events I’m not applying here. On original Flux definition
dispatching an event before previous one has finish is forbidden and
will throw an exception. To keep the project simple I’m not
implementing that here.
Dispatcher是使用了Otto事件总线实现。任何的事件总线也都可以的啦。在原来的Flux定义中,在上一个事件结束前就分发一个新的事件是不允许的,此时会抛出异常。为了代码比较简单,我在这个项目中并没有实现这个功能;
There is an ActionsCreator
class to help creating Actions
and
posting them into the Dispatcher
. It is a pretty common pattern in
Flux which keeps things organised.
ActionsCreator类用于创建Action和将它们投递到Dispatcher
。在Flux中这是一种比较常见的模式。
Actions
types are just String
constants. It is probably not the
best implementation but is quick and helps keeping things simple.
Action类型只有字符串常量。这也许不是最好的实现,但是是最快、最能保持简洁性的。
Same thing with Actions
data: they are just a HashMap
with a
String
key and Object
as a value. This forces ugly castings on
Stores to extract actual data. Of course, this is not type safe but
again, keeps the example easy to understand.
Action中的数据也只是使用key为String、value为Object类型的HashMap
来存储。因此这需要你在Store中进行强制类型转换,一般得到具体的Action数据。当然,这并不是类型安全的,还是那句话 : 为了保持简单性。
==========
There is no such thing as the Best Architecture for an Android app. There is the Best Architecture for your current app. And it is the one that let you collaborate with your teammates easily, finish the project on time, with quality and as less bugs as possible.
没有什么最好的Android应用架构,只有最适合你应用的架构。这个架构能够使你你和你的队友很方便地一起协作,在规定的时间内高质量的完成你的应用。
I believe Flux is very good for all of that.
我相信Flux架构在这些方面还是比较靠谱的,不信就自己动手试试吧!
京东创始人刘强东和其妻子章泽天最近成为了互联网舆论关注的焦点。有关他们“移民美国”和在美国购买豪宅的传言在互联网上广泛传播。然而,京东官方通过微博发言人发布的消息澄清了这些传言,称这些言论纯属虚假信息和蓄意捏造。
日前,据博主“@超能数码君老周”爆料,国内三大运营商中国移动、中国电信和中国联通预计将集体采购百万台规模的华为Mate60系列手机。
据报道,荷兰半导体设备公司ASML正看到美国对华遏制政策的负面影响。阿斯麦(ASML)CEO彼得·温宁克在一档电视节目中分享了他对中国大陆问题以及该公司面临的出口管制和保护主义的看法。彼得曾在多个场合表达了他对出口管制以及中荷经济关系的担忧。
今年早些时候,抖音悄然上线了一款名为“青桃”的 App,Slogan 为“看见你的热爱”,根据应用介绍可知,“青桃”是一个属于年轻人的兴趣知识视频平台,由抖音官方出品的中长视频关联版本,整体风格有些类似B站。
日前,威马汽车首席数据官梅松林转发了一份“世界各国地区拥车率排行榜”,同时,他发文表示:中国汽车普及率低于非洲国家尼日利亚,每百户家庭仅17户有车。意大利世界排名第一,每十户中九户有车。
近日,一项新的研究发现,维生素 C 和 E 等抗氧化剂会激活一种机制,刺激癌症肿瘤中新血管的生长,帮助它们生长和扩散。
据媒体援引消息人士报道,苹果公司正在测试使用3D打印技术来生产其智能手表的钢质底盘。消息传出后,3D系统一度大涨超10%,不过截至周三收盘,该股涨幅回落至2%以内。
9月2日,坐拥千万粉丝的网红主播“秀才”账号被封禁,在社交媒体平台上引发热议。平台相关负责人表示,“秀才”账号违反平台相关规定,已封禁。据知情人士透露,秀才近期被举报存在违法行为,这可能是他被封禁的部分原因。据悉,“秀才”年龄39岁,是安徽省亳州市蒙城县人,抖音网红,粉丝数量超1200万。他曾被称为“中老年...
9月3日消息,亚马逊的一些股东,包括持有该公司股票的一家养老基金,日前对亚马逊、其创始人贝索斯和其董事会提起诉讼,指控他们在为 Project Kuiper 卫星星座项目购买发射服务时“违反了信义义务”。
据消息,为推广自家应用,苹果现推出了一个名为“Apps by Apple”的网站,展示了苹果为旗下产品(如 iPhone、iPad、Apple Watch、Mac 和 Apple TV)开发的各种应用程序。
特斯拉本周在美国大幅下调Model S和X售价,引发了该公司一些最坚定支持者的不满。知名特斯拉多头、未来基金(Future Fund)管理合伙人加里·布莱克发帖称,降价是一种“短期麻醉剂”,会让潜在客户等待进一步降价。
据外媒9月2日报道,荷兰半导体设备制造商阿斯麦称,尽管荷兰政府颁布的半导体设备出口管制新规9月正式生效,但该公司已获得在2023年底以前向中国运送受限制芯片制造机器的许可。
近日,根据美国证券交易委员会的文件显示,苹果卫星服务提供商 Globalstar 近期向马斯克旗下的 SpaceX 支付 6400 万美元(约 4.65 亿元人民币)。用于在 2023-2025 年期间,发射卫星,进一步扩展苹果 iPhone 系列的 SOS 卫星服务。
据报道,马斯克旗下社交平台𝕏(推特)日前调整了隐私政策,允许 𝕏 使用用户发布的信息来训练其人工智能(AI)模型。新的隐私政策将于 9 月 29 日生效。新政策规定,𝕏可能会使用所收集到的平台信息和公开可用的信息,来帮助训练 𝕏 的机器学习或人工智能模型。
9月2日,荣耀CEO赵明在采访中谈及华为手机回归时表示,替老同事们高兴,觉得手机行业,由于华为的回归,让竞争充满了更多的可能性和更多的魅力,对行业来说也是件好事。
《自然》30日发表的一篇论文报道了一个名为Swift的人工智能(AI)系统,该系统驾驶无人机的能力可在真实世界中一对一冠军赛里战胜人类对手。
近日,非营利组织纽约真菌学会(NYMS)发出警告,表示亚马逊为代表的电商平台上,充斥着各种AI生成的蘑菇觅食科普书籍,其中存在诸多错误。
社交媒体平台𝕏(原推特)新隐私政策提到:“在您同意的情况下,我们可能出于安全、安保和身份识别目的收集和使用您的生物识别信息。”
2023年德国柏林消费电子展上,各大企业都带来了最新的理念和产品,而高端化、本土化的中国产品正在不断吸引欧洲等国际市场的目光。
罗永浩日前在直播中吐槽苹果即将推出的 iPhone 新品,具体内容为:“以我对我‘子公司’的了解,我认为 iPhone 15 跟 iPhone 14 不会有什么区别的,除了序(列)号变了,这个‘不要脸’的东西,这个‘臭厨子’。