练习(2):
字符串列表”one”, “two”, “three”,”four”,”five”,要求每隔2秒按顺序输出字符串。
代码如下:
public class MainActivity extends Activity {
@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("one", "two", "three", "four", "five");
Subscriber<Long> subscriber = 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) {
int i = l.intValue();
if (i == list.size()) {
this.unsubscribe();
onCompleted();
}
text.setText(list.get(i));
Log.d("Toast", "l = " + l);
}
};
Observable.interval(2, 2, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
}
本练习主要使用interval方法。该方法会创建一个Observable对象,按照预设的时间,间隔和时间单位发送一个事件。