RxJava1.6订阅和取消订阅

/**
 * @author ChenYe
 *         implementation 'io.reactivex:rxjava:1.1.6'
 *         implementation 'io.reactivex:rxandroid:1.2.1'
 *         RxJava的观察者和被观察者,当观察者的代码块完全走完之后(请看清楚,我说的完全,不是说执行一次之后),
 *         就会自动取消订阅,然后观察者的一个方法subscriber.isUnsubscribed(),返回true代表已经取消订阅了,
 *         返回false代表还在订阅中,而这个时候执行 subscriber.unsubscribe();就可以取消订阅
 */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "cy==MainActivity";
    private Observable observable;
    private Subscriber subscriber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        observable = Observable.interval(10, TimeUnit.SECONDS)
                .map(new Func1() {
                    @Override
                    public String call(Long aLong) {
                        return "这是测试数据";
                    }
                });
        subscriber = Subscribers.create(new Action1() {
            @Override
            public void call(String s) {
                Log.e(TAG, s);
            }
        });

    }


    public void subAndExecute(View view) {
        observable.subscribe(subscriber);
    }

    public void cancelSub(View view) {

        if (!subscriber.isUnsubscribed()) {
            subscriber.unsubscribe();
        }
    }

    public void judge(View view) {
        //指示此订阅者是否已从其订阅列表取消订阅。
        if (subscriber.isUnsubscribed()) {
            Log.e(TAG, "已经取消了订阅");
        } else {
            Log.e(TAG, "还没有取消订阅");
        }
    }

}

你可能感兴趣的:(RxJava学习)