package ccpg.lostjson;
import android.content.Context;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Lostboy船长 on 2018/9/7.
*/
通过单例模式实现线程之间数据回调。本想用Hash把数据存储起来,已待需要时候提取。
觉得对象处理还是简单些好
public class NRxBus {
private static NRxBusnRxBus;
//集合对象
private List
private NRxBus() {
}
//初始化单例模式
public static NRxBus getNRxbus(){
if (nRxBus==null){
synchronized (NRxBus.class){
if (nRxBus==null){
nRxBus=new NRxBus();
}
}
}
return nRxBus;
}
//setData 用于Activity之间监听数据,做到及时更新
public synchronized NRxBus setData(String value,String tag){
if (!TextUtils.isEmpty(tag)&&!TextUtils.isEmpty(value)&&!nRxObjects.isEmpty()){
for (NRxObject nrx:nRxObjects) {
if (nrx.tag.equals(tag)){
//被观察者数据提取
nrx.callData.calldata(value);
}
}
}
return this;
}
//添加监听对象
public synchronized NRxBus addnRxObject(NRxObject nRxObject){
if (nRxObject!=null&&nRxObject.callData!=null)
nRxObjects.add(nRxObject);
return this;
}
//移除绑定监听对象
public synchronized NRxBus removenRxObject(Context context){
if (context!=null){
//初始位置
int loPosition=0;
for (int i =0; i if (nRxObjects.get(i).equals(context)) { nRxObjects.remove(i-loPosition); loPosition++; } } } return this; } //清除集合 public synchronized void clearObject(){ nRxObjects.clear(); } //获取集合大小 public synchronized int getSize(){ return nRxObjects.size(); } //回调绑定对象 public static class NRxObject{ private Stringtag; private JPCallData callData; private Stringname; //context 文本类名 tag 数据传输标签 calldata 回调接口 public NRxObject(Context context,String tag, JPCallData callData) { this.name=context.getClass().getName(); this.tag = tag; this.callData = callData; } //重写equals @Override public boolean equals(Object obj) { if (obj==null){ return false; } return this.name.equals(obj.getClass().getName()); } } //回调接口 public interface JPCallData{ void calldata(String s); } }