本例主要讲skip和take的使用
还是练习2的代码,只不过需要跳过前2个,从第三个开始显示
代码如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = (TextView) findViewById(R.id.text);
List<String> list = Arrays.asList("hi", "hello", "hey", "ha", "hoo");
Observable.interval(2, 2, TimeUnit.SECONDS)
// .skip(2)
.take(list.size())
.skip(2)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Long>() {
@Override
public void onCompleted() {
Toast.makeText(MainActivity.this, "Complete", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long l) {
text.setText(list.get(l.intValue()));
}
});
}
}
请注意skip放到take之前和之后的区别。
放到take之前,complete的toast不会显示。
放到take之后,complete的toast会显示。
take的解释
public final Observable take(int num)
Returns an Observable that emits only the first num items emitted by the source Observable.
返回一个Observable对象,该对象只会释放从源Observable对象释放的前num个事件。
对应java的代码:
count = 0;
while (count < 5) {
text.settext(list.get(count))
count++;
}
skip的解释
public final Observable skip(int num)
Returns an Observable that skips the first num items emitted by the source Observable and emits the remainder.
返回一个Observable对象,该对象会跳过源Observable对象释放的前num个对象,然后释放剩余的
对应的java代码:
count = 0;
while (count < 5) {
if (count < 2) continue;
text.settext(list.get(count))
count++;
}