Android_RxBus传值

一:使用RxJava模仿EventBus传值,快速方便

 依赖:

compile 'io.reactivex:rxjava:1.3.4'
compile 'io.reactivex:rxandroid:1.2.1'

二:工具类

public class RxBus {
    private static volatile RxBus instance;

    private SerializedSubject bus;

    public RxBus() {
        bus = new SerializedSubject(PublishSubject.create());
    }

    public static RxBus getInstance() {
        if (instance == null) {
            synchronized (RxBus.class) {
                if (null == instance) {
                    instance = new RxBus();
                }
            }
        }
        return instance;
    }

    //传入数据
    public void post(Object o){
        bus.onNext(o);
    }

    //返回类型--被观察者
    public  Observable tObservable(Class event) {
        return bus.ofType(event);
    }


}


三:使用

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class RxbusActivity extends AppCompatActivity {

    private TextView tv;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rxbus);
        tv = (TextView)findViewById(R.id.tv);
        btn = (Button)findViewById(R.id.btn);
        //点击发送值
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RxBus.getInstance().post("Android Stuio");
            }
        });
        //得到被观察者
        Observable observable = RxBus.getInstance().tObservable(String.class);
        //观察者查看
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1() {
                    @Override
                    public void call(String s) {
                        //改变TextView值
                        tv.setText(s);
                    }
                });
    }
}



你可能感兴趣的:(Android_RxBus传值)