RxJava/RxAndroid:repeatUntil Bertha 。 2023-10-17 17:57 46阅读 0赞 **RxJava/RxAndroid:repeatUntil** import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.functions.BooleanSupplier; import io.reactivex.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { private String TAG = "输出"; private Observer<Integer> mObserver = new Observer<Integer>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Integer i) { Log.d(TAG, "onNext:" + i); } @Override public void onComplete() { Log.d(TAG, "onComplete"); } @Override public void onError(Throwable e) { Log.e(TAG, e.toString(), e); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Integer[] numbers = new Integer[]{0, 1, 2, 3, 4}; Observable.fromArray(numbers) .repeatUntil(new BooleanSupplier() { @Override public boolean getAsBoolean() throws Exception { boolean b; int rand = (int) (Math.random() * 10); Log.d(TAG, "随机数:" + rand); //如果随机产生的整数大于5,停止重复。 if (rand > 5) { b = true; } else { b = false; } Log.d(TAG, "getAsBoolean:" + b); return b; } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .subscribeWith(mObserver); } } output: 01-24 14:57:16.630 9047-9067/zhangphil.book D/输出: 随机数:2 01-24 14:57:16.631 9047-9067/zhangphil.book D/输出: getAsBoolean:false 01-24 14:57:16.631 9047-9067/zhangphil.book D/输出: 随机数:9 01-24 14:57:16.631 9047-9067/zhangphil.book D/输出: getAsBoolean:true 01-24 14:57:16.647 9047-9068/zhangphil.book D/输出: onNext:0 01-24 14:57:16.647 9047-9068/zhangphil.book D/输出: onNext:1 01-24 14:57:16.647 9047-9068/zhangphil.book D/输出: onNext:2 01-24 14:57:16.647 9047-9068/zhangphil.book D/输出: onNext:3 01-24 14:57:16.647 9047-9068/zhangphil.book D/输出: onNext:4 01-24 14:57:16.647 9047-9068/zhangphil.book D/输出: onNext:0 01-24 14:57:16.647 9047-9068/zhangphil.book D/输出: onNext:1 01-24 14:57:16.647 9047-9068/zhangphil.book D/输出: onNext:2 01-24 14:57:16.647 9047-9068/zhangphil.book D/输出: onNext:3 01-24 14:57:16.647 9047-9068/zhangphil.book D/输出: onNext:4 01-24 14:57:16.647 9047-9068/zhangphil.book D/输出: onComplete
还没有评论,来说两句吧...