LoginSignup
14
10

More than 5 years have passed since last update.

AndroidでRxを使って一定間隔に値を流したいとき

Posted at
  • Tipsというか、どうやるのがスマートなのかなと悩みながらこんな感じにしましたというものなので、こうすれば簡単だよ!というのがあればご教示ください m(_ _)m

やりたいこと

List<String> textList = new ArrayList<>();
textList.add("hoge");
textList.add("fuga");
textList.add("piyo");
textList.add("nya-");

という感じなリストがあったときに、これを定期的に、例えば1秒置きに1つずつ値を流したい、という話です。AndroidではHandlerでpostDelayedするのを繰り返せばできますが、それをRxでいい感じに書きたいのです。

こうしてみた

List<String> textList = new ArrayList<>();
textList.add("hoge");
textList.add("fuga");
textList.add("piyo");
textList.add("nya-");

Subscription subscription = Observable.interval(1, TimeUnit.SECONDS).take(textList.size()).subscribe(indexL -> {
    int index = indexL.intValue();
    System.out.println(textList.get(index));
});
  • 最初にintervalで1秒置きに数値が流れる無限Streamを作ってから、listの数だけtakeしてsubscribeの中で流れてきた値をindexとして使ってListにアクセスしています。Androidの場合は作ったSubscriptionをonPauseでunsubscribeした方がよいでしょう。
14
10
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
10