|
| 1 | +package com.che58.ljb.rxjava.fragment; |
| 2 | + |
| 3 | +import android.os.Bundle; |
| 4 | +import android.support.annotation.Nullable; |
| 5 | +import android.view.LayoutInflater; |
| 6 | +import android.view.View; |
| 7 | +import android.view.ViewGroup; |
| 8 | +import android.widget.Toast; |
| 9 | + |
| 10 | +import com.che58.ljb.rxjava.R; |
| 11 | +import com.trello.rxlifecycle.components.support.RxFragment; |
| 12 | + |
| 13 | +import butterknife.ButterKnife; |
| 14 | +import butterknife.OnClick; |
| 15 | +import rx.Observable; |
| 16 | +import rx.Observer; |
| 17 | +import rx.android.schedulers.AndroidSchedulers; |
| 18 | + |
| 19 | +/** |
| 20 | + * 复用订阅者Demo |
| 21 | + * Created by ljb on 2016/4/29. |
| 22 | + */ |
| 23 | +public class ReuseSubscriberFragment extends RxFragment { |
| 24 | + |
| 25 | + |
| 26 | + private Observer mReuseSubscriber; |
| 27 | + |
| 28 | + @Nullable |
| 29 | + @Override |
| 30 | + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { |
| 31 | + View view = inflater.inflate(R.layout.fragment_reuse_subscriber, null); |
| 32 | + ButterKnife.bind(this, view); |
| 33 | + return view; |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public void onActivityCreated(@Nullable Bundle savedInstanceState) { |
| 38 | + super.onActivityCreated(savedInstanceState); |
| 39 | + initData(); |
| 40 | + } |
| 41 | + |
| 42 | + private void initData() { |
| 43 | + //订阅者 |
| 44 | + mReuseSubscriber = new Observer<Object>() { |
| 45 | + @Override |
| 46 | + public void onCompleted() { |
| 47 | + |
| 48 | + } |
| 49 | + |
| 50 | + @Override |
| 51 | + public void onError(Throwable e) { |
| 52 | + |
| 53 | + } |
| 54 | + |
| 55 | + @Override |
| 56 | + public void onNext(Object data) { |
| 57 | + if (data.getClass() == Integer.class) { |
| 58 | + Toast.makeText(getActivity(), "The data from Btn1!", Toast.LENGTH_SHORT).show(); |
| 59 | + } else if (data.getClass() == String.class) { |
| 60 | + Toast.makeText(getActivity(), "The data from Btn2!", Toast.LENGTH_SHORT).show(); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + //被观察者1 |
| 65 | + @OnClick(R.id.btn1) |
| 66 | + void btn1() { |
| 67 | + Observable.just(1) |
| 68 | + .compose(this.<Integer>bindToLifecycle()) |
| 69 | + .observeOn(AndroidSchedulers.mainThread()) |
| 70 | + .subscribe(mReuseSubscriber); |
| 71 | + } |
| 72 | + |
| 73 | + //被观察者2 |
| 74 | + @OnClick(R.id.btn2) |
| 75 | + void btn2() { |
| 76 | + Observable.just("string") |
| 77 | + .compose(this.<String>bindToLifecycle()) |
| 78 | + .observeOn(AndroidSchedulers.mainThread()) |
| 79 | + .subscribe(mReuseSubscriber); |
| 80 | + } |
| 81 | +} |
0 commit comments