您的位置:首页 > 编程语言 > Java开发

RxJava练习(2)--时间间隔输出字符串

2015-12-30 23:07 471 查看
练习(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对象,按照预设的时间,间隔和时间单位发送一个事件。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  RxJava