本文主要是介绍RxJava2 / RxAndroid2操作符take,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
take操作获取一系列Observable输出结果的之前的数据作为最终输出,以后的不予处理,例如代码:
package zhangphil.app;import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;public class MainActivity extends AppCompatActivity {private final String TAG = getClass().getSimpleName();private CompositeDisposable mCompositeDisposable = new CompositeDisposable();@Overridepublic void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);test();}private void test() {DisposableObserver disposableObserver = new DisposableObserver<Integer>() {@Overridepublic void onNext(Integer i) {Log.d(TAG, "#####开始#####");Log.d(TAG + "数据", String.valueOf(i));Log.d(TAG, "#####结束#####");}@Overridepublic void onComplete() {Log.d(TAG, "onComplete");}@Overridepublic void onError(Throwable e) {Log.e(TAG, e.toString(), e);}};mCompositeDisposable.add(getObservable().take(6).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribeWith(disposableObserver));}private Observable<Integer> getObservable() {return Observable.range(1, 10);}@Overrideprotected void onDestroy() {super.onDestroy();// 如果退出程序,就清除后台任务mCompositeDisposable.clear();}
}
代码输出:
05-15 16:59:19.084 7024-7024/zhangphil.app D/MainActivity: #####开始#####
05-15 16:59:19.084 7024-7024/zhangphil.app D/MainActivity数据: 1
05-15 16:59:19.084 7024-7024/zhangphil.app D/MainActivity: #####结束#####
05-15 16:59:19.084 7024-7024/zhangphil.app D/MainActivity: #####开始#####
05-15 16:59:19.084 7024-7024/zhangphil.app D/MainActivity数据: 2
05-15 16:59:19.084 7024-7024/zhangphil.app D/MainActivity: #####结束#####
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity: #####开始#####
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity数据: 3
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity: #####结束#####
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity: #####开始#####
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity数据: 4
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity: #####结束#####
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity: #####开始#####
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity数据: 5
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity: #####结束#####
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity: #####开始#####
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity数据: 6
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity: #####结束#####
05-15 16:59:19.085 7024-7024/zhangphil.app D/MainActivity: onComplete
这篇关于RxJava2 / RxAndroid2操作符take的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!