Skip to content

Instantly share code, notes, and snippets.

@YusukeIwaki
Created January 23, 2017 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YusukeIwaki/c349f711cc8c8e5d48fe2da0469c007a to your computer and use it in GitHub Desktop.
Save YusukeIwaki/c349f711cc8c8e5d48fe2da0469c007a to your computer and use it in GitHub Desktop.
flatMapしてるものは、unsubscribeしたら実行されないよね確認
import rx.Observable;
import rx.Single;
import rx.Subscription;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class Hoge {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(2);
SingleGenerator generator = new SingleGenerator(countDownLatch);
Subscription subscription = generator.generate()
.flatMap(_val -> generator.generate())
.flatMap(_val -> generator.generate())
.flatMap(_val -> generator.generate())
.subscribe();
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-- unsub --");
subscription.unsubscribe();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("== exit ==");
}
private static class SingleGenerator {
private int i;
private final CountDownLatch countDownLatch;
public SingleGenerator(CountDownLatch countDownLatch) {
i = 0;
this.countDownLatch = countDownLatch;
}
private Single<Integer> generate() {
return Observable.timer(2, TimeUnit.SECONDS)
.toSingle()
.flatMap(_val -> Single.just(i++))
.doOnSuccess(val -> {
System.out.println(val);
countDownLatch.countDown();
});
}
}
}
@YusukeIwaki
Copy link
Author

ubsubした場合

0
1
-- unsub --
== exit ==

ubsubしなかった場合

0
1
-- unsub --
2
3
== exit ==

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment