1.创建类工具类”
public class MLiveDataBus {
private static MLiveDataBus liveDataBus = new MLiveDataBus();
private HashMap<String, MutableLiveData<Object>> map;
private MLiveDataBus() {
map = new HashMap<>();
}
public static MLiveDataBus getDefault() {
return liveDataBus;
}
public synchronized <T> MutableLiveData<T> post(Class<T> type) {
String simpleName = type.getSimpleName();
Log.d("TAG", "post: " + simpleName);
if (!map.containsKey(simpleName)) {
map.put(simpleName, new MutableLiveData<>());
}
return (MutableLiveData<T>) map.get(simpleName);
}
public synchronized <T> void remove(Class<T> type) {
String simpleName = type.getSimpleName();
Log.d("TAG", "post: " + simpleName);
if (map.containsKey(simpleName)) {
map.remove(simpleName);
}
}
}
2.发送数据:
MLiveDataBus.getDefault().post(WeatherEvent.class).postValue(weatherEvent);
3.接受数据:
MLiveDataBus.getDefault().post(WeatherEvent.class).observe(this, new Observer<WeatherEvent>() {
@Override
public void onChanged(WeatherEvent weatherBean) {
weather = weatherBean;
binding.tvLocation.setText(weatherBean.getCity());
binding.scrollTextView.setText(weatherBean.getWeather());
}
});
772





