该项目基于RxJava2 & RxAndroid,并且从AndroidKnife/RxBus中学习而实现的。
使用annotation processing(注释处理)自动生成模板代码,避免了反射带来的性能影响。通过@Subscribe
标记订阅方法,@Rxthread
可设置订阅方法的运行线程,线程支持RxJava
中提供的6种线程:MainThread
、IO
、Computation
、Single
、NewThread
、Trampoline
。
在gradle中加入:
dependencies {compile 'com.github.vitess:rxbus:2.0.2'annotationProcessor 'com.github.vitess:rxbus-compiler:2.0.2'
}
开发版本的快照可从Sonatype’s snapshots repository中找到。
在类的初始化处使用RxBus.register
注册,并在类销毁的地方使用RxBus.unregister
注销。注册后的类中的方法即可使用@Subscribe
注释标记,此后在类以外的地方即可通过RxBus.post
发射数据到指定方法中。
当使用@Subscribe
标记方法时,若不指定特定的tag,该方法将被默认的tag所标记。这一类被默认tag标记的方法可接收RxBus.post(Object value)
发射数据,或者使用RxBus.post(Subscribe.DEFAULT , ${value})
来显式发射。
For example:
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);RxBus.register(this);//TODO something...findViewById(R.id.button).setOnClickListenernew(View.OnClickListener() {@Overridepublic void onClick(View v) {RxBus.post("receiver1", 123);//post to receiver1RxBus.post("This is post to receiver2");//post to receiver2RxBus.post(new Object());//post to receiver3RxBus.post("receiver4", null);//post to receiver4RxBus.post(null);//post to receiver5}});}@Overrideprotected void onDestroy() {super.onDestroy();RxBus.unregister(this);}@Subscribe("receiver1")@RxThread(ThreadType.IO)public void receiver1(int random) {Log.i("RxBus", "receiver1:" + Thread.currentThread().getName());}@Subscribe@RxThread(ThreadType.Single)public void receiver2(String str) {Log.i("RxBus", "receiver2:" + Thread.currentThread().getName());}@Subscribepublic void receiver3(Object obj) {Log.i("RxBus", "receiver3:" + Thread.currentThread().getName());}@Subscribe("receiver4")public void receiver4(){Log.i("RxBus", "receiver4:" + Thread.currentThread().getName());}@Subscribepublic void receiver5(){Log.i("RxBus", "receiver5:" + Thread.currentThread().getName());}
}
目前思路稍微有些瓶颈,如果有好点子或者有可改进的地方,欢迎pull request,thanks!
post
方法发射,每次独立生成Single
完成操作;使用频率较高且生命周期较长的使用continuePost
方法发射,仅生成Processor
完成操作Copyright 2017 Vincent TamLicensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.