RxJava模型学习
0 参考
1 理论知识
1 原理
2 模式
3 extends和super泛型区别
2 模拟代码
代表XXX动作—-发出者动作
public interface Action1<T> {
void call(T subscrible);
}
代表XXX的女生—事件响应者,观察者 public interface SubScrible
代表XXX的男生—事件发出者,被观察者,持有观察者引用,手动向观察者发出命令
public interface OnSubscrible<T> extends Action1<SubScrible<? super T>> {
@Override
void call(SubScrible<? super T> subscrible);
}
代表男生追女生的一个美丽的场景,里面有男生和女生,男生是被观察者,女生是观察者。
public class Obserable<T> {
public OnSubscrible<T> mOnSubscribe;
public Obserable(OnSubscrible<T> subscribe) {
this.mOnSubscribe = subscribe;
}
public void subscrible(SubScrible<? super T> subScrible) {
this.mOnSubscribe.call(subScrible);
}
@SuppressWarnings("unchecked")
public static <T> Obserable create(OnSubscrible<T> subscribe) {
return new Obserable(subscribe);
}
@SuppressWarnings("unchecked")
public <R> Obserable<R> map(Func1<? super T,? extends R> func1){
OnSubscribleLift<T,R> lift= new OnSubscribleLift<T,R>(func1,mOnSubscribe);
return new Obserable(lift) ;
}
}
有一个男生,想找一个看电影女生,场景给他一个女生,然后男生说走看电影去,女生说好的。
Obserable.create(new OnSubscrible<String>() {
@Override
public void call(SubScrible<? super String> subscrible) {
Log.v("test", "男生:看电影去吧");
subscrible.onNext("男生:看电影去吧");
}
}).subscrible(new SubScrible<String>() {
@Override
public void onNext(String sub) {
Log.v("test", "女生:走一起去看电影咯");
}
});
事件变换:男生想找个开房的女生,自己只能找到看电影的女生,于是就找好兄弟帮忙,好兄弟让自己女朋友去,女朋友不愿意去,女朋友又找来一个能开房的闺蜜。
//变换
public interface Func1<T,R> {
R call(T subscrble );
}
public class OnSubscribleLift<T, R> implements OnSubscrible<R> {
private Func1<? super T, ? extends R> func1;
private OnSubscrible<T> onSubscrible;
public OnSubscribleLift(Func1<? super T, ? extends R> func1, OnSubscrible<T> boy) {
this.func1 = func1;
this.onSubscrible = boy;
}
@Override
public void call(SubScrible<? super R> subscrible) {
Operachange<T, R> kissGirl = new Operachange<T, R>(subscrible, func1);
onSubscrible.call(kissGirl);
}
private class Operachange<T, R> implements SubScrible<T> {
private SubScrible<? super R> mResult;
private Func1<? super T, ? extends R> func1;
public Operachange(SubScrible<? super R> mResult, Func1<? super T, ? extends R> func1) {
this.mResult = mResult;
this.func1 = func1;
}
@Override
public void onNext(T sub) {
R t = this.func1.call(sub);
mResult.onNext(t);
}
}
测试
Obserable.create(new OnSubscrible<String>() {
@Override
public void call(SubScrible<? super String> subscrible) {
subscrible.onNext("好兄弟:给你找个看电影的女生");
}
}).map(new Func1<String, Bitmap>() {
@Override
public Bitmap call(String subscrble) {
Log.v("test", "没找到看电影女生");
return null;
}
}).subscrible(new SubScrible<Bitmap>() {
@Override
public void onNext(Bitmap sub) {
Log.v("test", "女生:我不想看电影,想开房");
Log.v("test", "男生:其实我也想开房");
}
});
–