woshidan's loose leaf

ぼんやり勉強しています

RxJavaでやりたかったことが少しわかってきた

勉強が進んできて、ようやく

qiita.com

で紹介されていることの意味がわかってきて嬉しくなったので、今日はバックグラウンドのスレッドでしばらく待ってから、 UIスレッドでログを出す & それをボタン押して止める、みたいなサンプルを書きました。わいわい。

public class MainActivity extends AppCompatActivity {
    private Subscription mSubscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mSubscription = Observable.from(new Integer[]{1,2,3,4,5})
                .map(new Func1<Integer, Integer>() {
                    @Override
                    public Integer call(Integer integer) {
                        try {
                            Thread.sleep(1000l);
                        } catch (InterruptedException e) {
                        }
                        return integer;
                    }
                })
                .repeat()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                System.out.print("replay ex BEGIN: ");
                for (int i = 0; i < integer; i++) {
                    System.out.print("*");
                }
                System.out.println(" :END");
                Log.d("replay ex", "current Time:" + System.currentTimeMillis() + "ms");
            }
        });

       FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("replay ex", "unsubscribe");
                mSubscription.unsubscribe();
            }
        });
    }