ひよっこゲームブログ

なにもかも初心者のひよっこがゆったりと何かする

リアクティブプログラミング4日目

Javaエアプなのでちょくちょく調べないとあかん


サンプルコード

import io.reactivex.rxjava3.schedulers.Schedulers;

Flowable.fromCallable(() -> {
    Thread.sleep(1000); //  imitate expensive computation
    return "Done";
})
  .subscribeOn(Schedulers.io())
  .observeOn(Schedulers.single())
  .subscribe(System.out::println, Throwable::printStackTrace);

Thread.sleep(2000); // <--- wait for the flow to finish


fromCallable()って何
Callable (Java Platform SE 8)

Javaの関数型のインターフェースだそうだ、ほーん


書き直すとこうなるらしい

Flowable<String> source = Flowable.fromCallable(() -> {
    Thread.sleep(1000); //  imitate expensive computation
    return "Done";
});

Flowable<String> runBackground = source.subscribeOn(Schedulers.io());

Flowable<String> showForeground = runBackground.observeOn(Schedulers.single());

showForeground.subscribe(System.out::println, Throwable::printStackTrace);

Thread.sleep(2000);

バックグランドで入出力処理して、そのあとフォアグラウンドで処理してる。うむ


Schedulers

Schedulers.io() とかは「スケジューラー」と呼ばれる。まんまだな
これでスレッド操作とかするみたい

使用感がCoroutineのDispatchersみたいな感じだと思う(適当)


Javaのメインスレッドが終了した場合、スケジューラーは死ぬそうです。ふむふむ

ぱっと中身を見てみる

  • Schedulers.computation()
    バックグラウンドの固定のスレッド。ほとんどの処理はこれがデフォでいいみたい

  • Schedulers.io()
    動的なスレッド。ブロックできると書いてあるので処理待ちができるんだろう、たぶん

  • Schedulers.single()
    単一のスレッドで、FIFO方式(最初に入れたデータを最初に取り出す)

  • Schedulers.trampoline()
    テスト用。これもFIFO方式だそうです。まぁテスト用だし使わんやろ!(


明日を乗り切れば休みだー。リモートになってから曜日感覚がない