教你四步搞定RxBus.
1,在你的工程中添加依赖
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
<span style="color:#ff0000;"> <em>compile 'io.reactivex:rxjava:1.1.9'</em></span>
}
2,
在你的项目中添加Rxbus.java工具类,方便使用RxJava
import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;
public class RxBus {
private RxBus() {}
private static class SingleHolder {
public static RxBus mRxBus = new RxBus();
}
public static RxBus getInstance() {
return SingleHolder.mRxBus;
}
private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
public void send(Object o) {
_bus.onNext(o);
}
public Observable<Object> toObserverable() {
return _bus;
}
}
3,接下来就可以使用了
在需要的地方首先订阅.最后别忘了解除订阅.
package com.example.jiang_yan.rxbus;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import rx.Subscription;
import rx.functions.Action1;
/**
* Created by jiang_yan on 2016/8/25.
*/
public class B extends Activity{
private Subscription mSubscribe;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b);
tv = (TextView) findViewById(R.id.tv_b);
//订阅
subscribeRxBus();
}
/**
订阅
****/
private void subscribeRxBus() {
mSubscribe = RxBus.getInstance().toObserverable().subscribe(new Action1<Object>() {
@Override
public void call(Object o) {
//在这里就是收到的发送来的数据
Log.e("RxBus", "call: " + o);
if (o instanceof CharSequence) {
tv.setText(o.toString());
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mSubscribe != null && !mSubscribe.isUnsubscribed()) {
mSubscribe.unsubscribe();
}
}
}
4,发送数据(就更简单了)
其实就是一行代码
RxBus.getInstance().send("要发送的东西");
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import rx.Subscription;
public class MainActivity extends AppCompatActivity {
private Subscription mSubscribe;
Handler mHandler = new Handler();
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
//跳转到B
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,B.class));
}
});
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mHandler.postDelayed(this,1000);
RxBus.getInstance().send(System.currentTimeMillis()+"");
}
},1000);
}
}
完了,就这么简单.你会了吗?