[RxJava] just() vs fromCallable()
just()와 fromCallable()은같은 동작을 하는 것 같지만 차이점이 있다. just의 doc을 살펴보면
Note that the item is taken and re-emitted as is and not computed by any means byjust
. UsefromCallable(Callable)
to generate a single item on demand (whenObserver
s subscribe to it).
즉, just()는 모든 subscribe()에 동일한 값을 주기 때문에 subscribe() 할때 재연산이 필요하면 반드시 formCallable()을 사용해야 한다. 아래는 만들어본 예제.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | @Slf4j public class JustFromCallableTest { public static void main(String[] args) throws InterruptedException { log.info("start : {}", getTimeObject()); // 1. just() Observable<Long> justSource = Observable.just(getTimeObject()); justSource.subscribe(val -> log.info("just.onNext #1 : {}", val)); Thread.sleep(3000); justSource.subscribe(val -> log.info("just.onNext #2 : {}", val)); // 2. fromCallable() Observable<Long> callableSource = Observable.fromCallable(() -> getTimeObject()); callableSource.subscribe(val -> log.info("fromCallable.onNext #2 : {}", val)); Thread.sleep(3000); callableSource.subscribe(val -> log.info("fromCallable.onNext #2 : {}", val)); log.info("end: {}", getTimeObject()); } public static Long getTimeObject() { return Instant.now().getEpochSecond(); } } |
결과값는 아래와 같이 just()는 두번째 subscribe()에서도 처음의 결과값을 그대로 보내주고, fromCallable()은 subscribe() 할때마다 재연산 됨을 알 수 있다.
201| [main] INFO t.j.JustFromCallableTest - start : 1593097006 246| [main] INFO t.j.JustFromCallableTest - just.onNext #1 : 1593097006 3250| [main] INFO t.j.JustFromCallableTest - just.onNext #2 : 1593097006 3252| [main] INFO t.j.JustFromCallableTest - fromCallable.onNext #2 : 1593097009 6258| [main] INFO t.j.JustFromCallableTest - fromCallable.onNext #2 : 1593097012 6258| [main] INFO t.j.JustFromCallableTest - end: 1593097012
댓글
댓글 쓰기