本Demo是为了方便你们了解RxJava的API,我将全部的RxJava API(至少是官方文档中提到的)都写在一个android apk中,并在其中附以功能描述,代码示例,marble-diagram(Rx用来描述数据及其处理流程的图), 以及一些使用场景. 全部的资料都是在APK中,使用的时候不会消耗任何流量,并且你能够在任什么时候候任何地方学习使用.html
示例程序的特色以下:java
1. API涵盖全面: 包含了核心库及全部扩展实现库200个左右的API.python
2. 数据本地化,无需流量: 示例中的全部数据和图片都是本地加载的,因此无需消耗流量.android
3. 示例代码都是从源码中直接生成,因此看起来跟代码直接运行的效果是同样的markdown
上图为整个Demo的运行示例截图:网络
左边为Rxjava主要组件及运算符类别入口app
右边为单个运算符的marble-diagram, 详细的运算符列表,代码示例以及代码的执行结果。ide
点击相应的运算符,界面会切换到该运算符的marble-diagram以及示例代码,同时会执行该代码,将执行结果输出到结果区。性能
在整个Demo中,主要部分就是RxJava API运算子的呈现,包括marble图,API描述,示例代码,运算结果的展示学习
及不一样运算子切换的交互。
全部的UI组成部分都是以插件的形式插入到Demo的UI体系中,设计图以下:
APIBaseActivity: API详情主Activity,包含了重定向输出结果到结果view以及整合DisplayPluginManager中全部View的展现的功能。
DisplayPluginManager: 管理全部的展现Plugin。
Plugin: 展现Plugin的接口类,主要负责根据不一样的操做符ID提供不一样的插件View。
MarbleDiagramPlugin: Marble图展现插件。
DescriptionPlugin: API描述展现插件。
SampleCodePlugin: 示例代码展现插件。
下边详细介绍这四部分的核心实现:
marble图的地址是我在看官方文档的时候,手动扣取的,全部地址都保存在项目的MarbleDiagramPlugin.java中
最初demo使用的是动态获取marble图地址,因为原图须要消耗流量且图片较大,因此我是将全部图片从网络拉取到本地直接打包到apk中,并且在这个过程当中对图片进行了进一步的打包压缩。
读取marble地址配置
# 将原来的注册地址的代码块处理并读取出来 def ProcessRegisterBlock(lines): if len(lines) == 0: return None mb = [] for line in lines: line = line.strip('\r\n ,);') line = line.replace('\"',''); if len(line) < 10 or not line.startswith('http'): continue mb.append(line) return mb # 查找到Constants对应的Key def FindKey(line): start = line.find('Constants.') end = line.find(',',start) return line[start: end] # 将名称转化为android的资源描述符名称 def Url2Id(url): start = url.rfind('/') if start < 0: return None return 'R.drawable.' + url[start + 1:].replace('.','_').lower() codes = {} # 拼装待生成的目标代码的路径 dest = os.path.join('app','src','main','java','union','uc','com','rxjava_example','plugin') if not os.path.exists(dest): os.path.makedirs(dest) key = "" # 打开marble图地址配置源码文件,并逐行扫描处理 with open(os.path.join(dest, 'MarbleDiagramPlugin.java'), 'r') as input: block = [] find_add = False for line in input: if len(line.strip()) == 0: continue if line.find('add(Constants.') >= 0: find_add = True if len(block) > 0: code= ProcessRegisterBlock(block) codes[key] = code block = [] key = FindKey(line) http_start = line.find('\"http') if http_start >= 0: http_end = line.find('\"', http_start + 1) if http_end >= 0: block.append(line[http_start:http_end]) elif find_add: block.append(line) if find_add and len(block) > 0: code= ProcessRegisterBlock(block) codes[key] = code
2. 生成Marble图资源配置文件
# 新建marble图资源配置文件 with open(os.path.join(dest,'MarbleDiagram.java'),'w') as output: # 生成header header = ''' package union.uc.com.rxjava_example.plugin; import java.util.HashMap; import java.util.Map; import union.uc.com.rxjava_example.contants.Constants; import union.uc.com.rxjava_example.R; public class MarbleDiagram{ private Map<String, Integer[]> mCodes = new HashMap<>(); public MarbleDiagram(){ ''' footer = ''' } public Integer[] get(String key){ return mCodes.get(key); } private void add(String key, Integer... urls) { mCodes.put(key, urls); } } ''' output.write(header) # 生成footer for key,code in codes.items(): if code == None: continue s = "" if len(code) == 1: code0 = Url2Id(code[0]) s = '\nadd(%s,%s);' % (key, code0) elif len(code) == 2: code0 = Url2Id(code[0]) code1 = Url2Id(code[1]) s = '\nadd(%s,%s,%s);' % (key, code0, code1) elif len(code) == 3: code0 = Url2Id(code[0]) code1 = Url2Id(code[1]) code2 = Url2Id(code[2]) s = '\nadd(%s,%s,%s,%s);' % (key, code0, code1, code2) elif len(code) == 4: code0 = Url2Id(code[0]) code1 = Url2Id(code[1]) code2 = Url2Id(code[2]) code3 = Url2Id(code[3]) s = '\nadd(%s,%s,%s,%s,%s);' % (key, code0, code1, code2, code3) output.write(s) output.write(footer) #下载图片 dir_drawable = os.path.join('app', 'src', 'main', 'res', 'drawable') for key,code in codes.items(): if code != None: for c in code: os.system('wget %s -P imgs' % (c )) # 重命名图片 for root, dirs, files in os.walk('imgs'): for file in files: src = os.path.join(root,file) dest = os.path.join(dir_drawable, file.lower().replace('.', '_') + '.png') os.rename(src, dest)
3. 压缩图片,为减少API尺寸,对marble图进行了简单压缩
dir_drawable = os.path.join('app', 'src', 'main', 'res', 'drawable') for root, dirs, files in os.walk(dir_drawable): for file in files: if not file.endswith('.png'): continue src = os.path.join(root,file) img = Image.open(src) img = img.resize((400,200),Image.ANTIALIAS) img.save(src) del img
API描述UI插件的实现是在DescriptionPlugin中,该Plugin主要是根据操做符id生成TextView并设置内容文本。
public class DescriptionPlugin implements DisplayPluginManager.Plugin { @Override public Tuple.Tuple2<Observable<View>, View> getView(final Context context, String key) { // 建立描述TextView, 为提升内存性能,避免无效引用,使用WeakReference. final TextView textView = new TextView(context); final Reference<TextView> ref = new WeakReference<>(textView); Observable<View> o = Observable.just(key) .map(new Func1<String, Integer>() { @Override public Integer call(String s) { // 若是资源列表为空,则加载资源列表 if (mKeyToResource == null) { load(); } // 读取id对应的资源文本内容 return mKeyToResource.get(s); } }).map(new Func1<Integer, View>() { @Override public View call(Integer integer) { // 更新TextView 文本 textView.setText(integer); return textView; } }); return new Tuple.Tuple2<>(o, (View) textView); }
示例代码的实现是在SampleCodePlugin中,其实现逻辑是根据操做符id读取示例代码,并使用markdown view渲染。
public class SampleCodePlugin implements DisplayPluginManager.Plugin { @Override public Tuple.Tuple2<Observable<View>, View> getView(final Context context, String key) { // 建立Markdown view,使用weakreference,为了处理嵌入式touch事件的处理冲突,还须要重写其 onTeouchEvent方法。 MarkdownView markdownView = new MarkdownView(context){ @Override public boolean onTouchEvent(MotionEvent event) { requestDisallowInterceptTouchEvent(true); return super.onTouchEvent(event); } }; markdownView.setBackgroundColor(Color.LTGRAY); final Reference<MarkdownView> ref = new WeakReference<>(markdownView); Observable<View> o = Observable.just(key) // .observeOn(Schedulers.io()) .map(new Func1<String, String>() { @Override public String call(String s) { // 根据id获取示例代码,示例代码已经提早生成。 return mSampleCode.get(s); } }) .observeOn(Schedulers.from(UIThreadExecutor.SINGLETON)) .map(new Func1<String, View>() { @Override public View call(String s) { // 使用markdownview加载示例代码 MarkdownView mv = ref.get(); if (mv != null) { mv.loadMarkdown(s); } return mv; } }); return new Tuple.Tuple2<>(o, (View) markdownView); }
每当点击操做符以后,界面更新的同时,程序也会执行该操做符对应的示例代码,并将示例代码结果输出到界面,输出的形式是重定向日志的方式,即将程序输出结果逐行append到结果输出界面。
如上图,为整个demo工程的项目结构截图,为一个通用的android项目结构图,其中的
README.md:为Rxjava及部分项目的介绍。
*.py文件:为自动生成marble图及示例代码的脚本。
本示例从逻辑到实现概要介绍如上,详细内容,请参考demo源码。