Search in sources :

Example 6 with Observer

use of io.reactivex.Observer in project RxJava by ReactiveX.

the class ObservableRetryTest method testSourceObservableCallsUnsubscribe.

@Test
public void testSourceObservableCallsUnsubscribe() throws InterruptedException {
    final AtomicInteger subsCount = new AtomicInteger(0);
    final TestObserver<String> ts = new TestObserver<String>();
    ObservableSource<String> onSubscribe = new ObservableSource<String>() {

        @Override
        public void subscribe(Observer<? super String> s) {
            BooleanSubscription bs = new BooleanSubscription();
            // https://github.com/ReactiveX/RxJava/issues/1024
            if (!bs.isCancelled()) {
                subsCount.incrementAndGet();
                s.onError(new RuntimeException("failed"));
                // it unsubscribes the child directly
                // this simulates various error/completion scenarios that could occur
                // or just a source that proactively triggers cleanup
                // FIXME can't unsubscribe child
                //                    s.unsubscribe();
                bs.cancel();
            } else {
                s.onError(new RuntimeException());
            }
        }
    };
    Observable.unsafeCreate(onSubscribe).retry(3).subscribe(ts);
    // 1 + 3 retries
    assertEquals(4, subsCount.get());
}
Also used : BooleanSubscription(io.reactivex.internal.subscriptions.BooleanSubscription) Observer(io.reactivex.Observer) Test(org.junit.Test)

Example 7 with Observer

use of io.reactivex.Observer in project RxJava by ReactiveX.

the class ObservableTimeoutWithSelectorTest method testTimeoutSelectorWithTimeoutAndOnNextRaceCondition.

@Test
public void testTimeoutSelectorWithTimeoutAndOnNextRaceCondition() throws InterruptedException {
    // Thread 1                                    Thread 2
    //
    // observer.onNext(1)
    // start timeout
    // unsubscribe timeout in thread 2          start to do some long-time work in "unsubscribe"
    // observer.onNext(2)
    // timeout.onNext(1)
    //                                          "unsubscribe" done
    //
    //
    // In the above case, the timeout operator should ignore "timeout.onNext(1)"
    // since "observer" has already seen 2.
    final CountDownLatch observerReceivedTwo = new CountDownLatch(1);
    final CountDownLatch timeoutEmittedOne = new CountDownLatch(1);
    final CountDownLatch observerCompleted = new CountDownLatch(1);
    final CountDownLatch enteredTimeoutOne = new CountDownLatch(1);
    final AtomicBoolean latchTimeout = new AtomicBoolean(false);
    final Function<Integer, Observable<Integer>> timeoutFunc = new Function<Integer, Observable<Integer>>() {

        @Override
        public Observable<Integer> apply(Integer t1) {
            if (t1 == 1) {
                // Force "unsubscribe" run on another thread
                return Observable.unsafeCreate(new ObservableSource<Integer>() {

                    @Override
                    public void subscribe(Observer<? super Integer> observer) {
                        observer.onSubscribe(Disposables.empty());
                        enteredTimeoutOne.countDown();
                        // force the timeout message be sent after observer.onNext(2)
                        while (true) {
                            try {
                                if (!observerReceivedTwo.await(30, TimeUnit.SECONDS)) {
                                    // CountDownLatch timeout
                                    // There should be something wrong
                                    latchTimeout.set(true);
                                }
                                break;
                            } catch (InterruptedException e) {
                            // Since we just want to emulate a busy method,
                            // we ignore the interrupt signal from Scheduler.
                            }
                        }
                        observer.onNext(1);
                        timeoutEmittedOne.countDown();
                    }
                }).subscribeOn(Schedulers.newThread());
            } else {
                return PublishSubject.create();
            }
        }
    };
    final Observer<Integer> o = TestHelper.mockObserver();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            observerReceivedTwo.countDown();
            return null;
        }
    }).when(o).onNext(2);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            observerCompleted.countDown();
            return null;
        }
    }).when(o).onComplete();
    final TestObserver<Integer> ts = new TestObserver<Integer>(o);
    new Thread(new Runnable() {

        @Override
        public void run() {
            PublishSubject<Integer> source = PublishSubject.create();
            source.timeout(timeoutFunc, Observable.just(3)).subscribe(ts);
            // start timeout
            source.onNext(1);
            try {
                if (!enteredTimeoutOne.await(30, TimeUnit.SECONDS)) {
                    latchTimeout.set(true);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // disable timeout
            source.onNext(2);
            try {
                if (!timeoutEmittedOne.await(30, TimeUnit.SECONDS)) {
                    latchTimeout.set(true);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            source.onComplete();
        }
    }).start();
    if (!observerCompleted.await(30, TimeUnit.SECONDS)) {
        latchTimeout.set(true);
    }
    assertFalse("CoundDownLatch timeout", latchTimeout.get());
    InOrder inOrder = inOrder(o);
    inOrder.verify(o).onSubscribe((Disposable) notNull());
    inOrder.verify(o).onNext(1);
    inOrder.verify(o).onNext(2);
    inOrder.verify(o, never()).onNext(3);
    inOrder.verify(o).onComplete();
    inOrder.verifyNoMoreInteractions();
}
Also used : InOrder(org.mockito.InOrder) Observable(io.reactivex.Observable) TestObserver(io.reactivex.observers.TestObserver) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Function(io.reactivex.functions.Function) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TestObserver(io.reactivex.observers.TestObserver) Observer(io.reactivex.Observer) Test(org.junit.Test)

Example 8 with Observer

use of io.reactivex.Observer in project RxJava by ReactiveX.

the class ObservableTimeoutWithSelectorTest method badSourceTimeout.

@Test
public void badSourceTimeout() {
    new Observable<Integer>() {

        @Override
        protected void subscribeActual(Observer<? super Integer> observer) {
            observer.onSubscribe(Disposables.empty());
            observer.onNext(1);
            observer.onNext(2);
            observer.onError(new TestException("First"));
            observer.onNext(3);
            observer.onComplete();
            observer.onError(new TestException("Second"));
        }
    }.timeout(Functions.justFunction(Observable.never()), Observable.<Integer>never()).take(1).test().assertResult(1);
}
Also used : TestException(io.reactivex.exceptions.TestException) TestObserver(io.reactivex.observers.TestObserver) Observer(io.reactivex.Observer) Observable(io.reactivex.Observable) Test(org.junit.Test)

Example 9 with Observer

use of io.reactivex.Observer in project RxJava by ReactiveX.

the class RxJavaPluginsTest method clearIsPassthrough.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void clearIsPassthrough() {
    try {
        RxJavaPlugins.reset();
        assertNull(RxJavaPlugins.onAssembly((Observable) null));
        assertNull(RxJavaPlugins.onAssembly((ConnectableObservable) null));
        assertNull(RxJavaPlugins.onAssembly((Flowable) null));
        assertNull(RxJavaPlugins.onAssembly((ConnectableFlowable) null));
        Observable oos = new Observable() {

            @Override
            public void subscribeActual(Observer t) {
            }
        };
        Flowable fos = new Flowable() {

            @Override
            public void subscribeActual(Subscriber t) {
            }
        };
        assertSame(oos, RxJavaPlugins.onAssembly(oos));
        assertSame(fos, RxJavaPlugins.onAssembly(fos));
        assertNull(RxJavaPlugins.onAssembly((Single) null));
        Single sos = new Single() {

            @Override
            public void subscribeActual(SingleObserver t) {
            }
        };
        assertSame(sos, RxJavaPlugins.onAssembly(sos));
        assertNull(RxJavaPlugins.onAssembly((Completable) null));
        Completable cos = new Completable() {

            @Override
            public void subscribeActual(CompletableObserver t) {
            }
        };
        assertSame(cos, RxJavaPlugins.onAssembly(cos));
        assertNull(RxJavaPlugins.onAssembly((Maybe) null));
        assertNull(RxJavaPlugins.onSchedule(null));
        Maybe myb = new Maybe() {

            @Override
            public void subscribeActual(MaybeObserver t) {
            }
        };
        assertSame(myb, RxJavaPlugins.onAssembly(myb));
        assertNull(RxJavaPlugins.onSchedule(null));
        Runnable action = Functions.EMPTY_RUNNABLE;
        assertSame(action, RxJavaPlugins.onSchedule(action));
        class AllSubscriber implements Subscriber, Observer, SingleObserver, CompletableObserver, MaybeObserver {

            @Override
            public void onSuccess(Object value) {
            }

            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onSubscribe(Subscription s) {
            }

            @Override
            public void onNext(Object t) {
            }

            @Override
            public void onError(Throwable t) {
            }

            @Override
            public void onComplete() {
            }
        }
        AllSubscriber all = new AllSubscriber();
        assertNull(RxJavaPlugins.onSubscribe(Observable.never(), null));
        assertSame(all, RxJavaPlugins.onSubscribe(Observable.never(), all));
        assertNull(RxJavaPlugins.onSubscribe(Flowable.never(), null));
        assertSame(all, RxJavaPlugins.onSubscribe(Flowable.never(), all));
        assertNull(RxJavaPlugins.onSubscribe(Single.just(1), null));
        assertSame(all, RxJavaPlugins.onSubscribe(Single.just(1), all));
        assertNull(RxJavaPlugins.onSubscribe(Completable.never(), null));
        assertSame(all, RxJavaPlugins.onSubscribe(Completable.never(), all));
        assertNull(RxJavaPlugins.onSubscribe(Maybe.never(), null));
        assertSame(all, RxJavaPlugins.onSubscribe(Maybe.never(), all));
        // These hooks don't exist in 2.0
        //            Subscription subscription = Subscriptions.empty();
        //
        //            assertNull(RxJavaPlugins.onObservableReturn(null));
        //
        //            assertSame(subscription, RxJavaPlugins.onObservableReturn(subscription));
        //
        //            assertNull(RxJavaPlugins.onSingleReturn(null));
        //
        //            assertSame(subscription, RxJavaPlugins.onSingleReturn(subscription));
        //
        //            TestException ex = new TestException();
        //
        //            assertNull(RxJavaPlugins.onObservableError(null));
        //
        //            assertSame(ex, RxJavaPlugins.onObservableError(ex));
        //
        //            assertNull(RxJavaPlugins.onSingleError(null));
        //
        //            assertSame(ex, RxJavaPlugins.onSingleError(ex));
        //
        //            assertNull(RxJavaPlugins.onCompletableError(null));
        //
        //            assertSame(ex, RxJavaPlugins.onCompletableError(ex));
        //
        //            Observable.Operator oop = new Observable.Operator() {
        //                @Override
        //                public Object call(Object t) {
        //                    return t;
        //                }
        //            };
        //
        //            assertNull(RxJavaPlugins.onObservableLift(null));
        //
        //            assertSame(oop, RxJavaPlugins.onObservableLift(oop));
        //
        //            assertNull(RxJavaPlugins.onSingleLift(null));
        //
        //            assertSame(oop, RxJavaPlugins.onSingleLift(oop));
        //
        //            Completable.CompletableOperator cop = new Completable.CompletableOperator() {
        //                @Override
        //                public CompletableSubscriber call(CompletableSubscriber t) {
        //                    return t;
        //                }
        //            };
        //
        //            assertNull(RxJavaPlugins.onCompletableLift(null));
        //
        //            assertSame(cop, RxJavaPlugins.onCompletableLift(cop));
        final Scheduler s = ImmediateThinScheduler.INSTANCE;
        Callable<Scheduler> c = new Callable<Scheduler>() {

            @Override
            public Scheduler call() throws Exception {
                return s;
            }
        };
        assertSame(s, RxJavaPlugins.onComputationScheduler(s));
        assertSame(s, RxJavaPlugins.onIoScheduler(s));
        assertSame(s, RxJavaPlugins.onNewThreadScheduler(s));
        assertSame(s, RxJavaPlugins.onSingleScheduler(s));
        assertSame(s, RxJavaPlugins.initComputationScheduler(c));
        assertSame(s, RxJavaPlugins.initIoScheduler(c));
        assertSame(s, RxJavaPlugins.initNewThreadScheduler(c));
        assertSame(s, RxJavaPlugins.initSingleScheduler(c));
    } finally {
        RxJavaPlugins.reset();
    }
}
Also used : ImmediateThinScheduler(io.reactivex.internal.schedulers.ImmediateThinScheduler) ConnectableFlowable(io.reactivex.flowables.ConnectableFlowable) Observable(io.reactivex.Observable) ConnectableObservable(io.reactivex.observables.ConnectableObservable) Observer(io.reactivex.Observer) ConnectableObservable(io.reactivex.observables.ConnectableObservable) ScalarSubscription(io.reactivex.internal.subscriptions.ScalarSubscription) ConnectableFlowable(io.reactivex.flowables.ConnectableFlowable) ParallelFlowable(io.reactivex.parallel.ParallelFlowable)

Example 10 with Observer

use of io.reactivex.Observer in project SpotiQ by ZinoKader.

the class LobbyPresenter method joinParty.

void joinParty(String partyTitle, String partyPassword) {
    Party party = new Party(partyTitle, partyPassword);
    Observable.zip(partiesRepository.getParty(party.getTitle()), spotifyRepository.getMe(spotifyCommunicatorService.getWebApi()), (dbPartySnapshot, spotifyUser) -> {
        if (dbPartySnapshot.exists()) {
            User user = new User(spotifyUser.id, spotifyUser.display_name, spotifyUser.images);
            boolean userAlreadyExists = dbPartySnapshot.child(FirebaseConstants.CHILD_USERS).hasChild(user.getUserId());
            Party dbParty = dbPartySnapshot.child(FirebaseConstants.CHILD_PARTYINFO).getValue(Party.class);
            return new UserPartyInformation(user, userAlreadyExists, dbParty);
        } else {
            throw new PartyDoesNotExistException();
        }
    }).map(userPartyInformation -> {
        if (userPartyInformation.getParty().getPassword().equals(partyPassword)) {
            if (!userPartyInformation.userAlreadyExists()) {
                partiesRepository.addUserToParty(userPartyInformation.getUser(), userPartyInformation.getParty().getTitle()).subscribe();
            }
            return userPartyInformation.getParty();
        } else {
            throw new PartyWrongPasswordException();
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Party>() {

        @Override
        public void onNext(Party party) {
            navigateToParty(party.getTitle());
        }

        @Override
        public void onError(Throwable exception) {
            if (exception instanceof PartyDoesNotExistException) {
                getView().showMessage("Party does not exist, why not create it?");
            } else if (exception instanceof PartyWrongPasswordException) {
                getView().showMessage("Password incorrect");
            } else {
                getView().showMessage("Something went wrong when joining the party");
            }
            Log.d(LogTag.LOG_LOBBY, "Could not join party");
            exception.printStackTrace();
        }

        @Override
        public void onComplete() {
        }

        @Override
        public void onSubscribe(Disposable d) {
        }
    });
}
Also used : PartiesRepository(se.zinokader.spotiq.repository.PartiesRepository) Bundle(android.os.Bundle) UserPrivate(kaaes.spotify.webapi.android.models.UserPrivate) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) Inject(javax.inject.Inject) SpotifyRepository(se.zinokader.spotiq.repository.SpotifyRepository) PartyExistsException(se.zinokader.spotiq.util.exception.PartyExistsException) FirebaseConstants(se.zinokader.spotiq.constant.FirebaseConstants) Observable(io.reactivex.Observable) Schedulers(io.reactivex.schedulers.Schedulers) Response(retrofit.client.Response) Log(android.util.Log) PartyNotCreatedException(se.zinokader.spotiq.util.exception.PartyNotCreatedException) LogTag(se.zinokader.spotiq.constant.LogTag) BasePresenter(se.zinokader.spotiq.feature.base.BasePresenter) UserPartyInformation(se.zinokader.spotiq.model.UserPartyInformation) UserNotAddedException(se.zinokader.spotiq.util.exception.UserNotAddedException) Party(se.zinokader.spotiq.model.Party) TimeUnit(java.util.concurrent.TimeUnit) Callback(retrofit.Callback) ApplicationConstants(se.zinokader.spotiq.constant.ApplicationConstants) Disposable(io.reactivex.disposables.Disposable) PartyDoesNotExistException(se.zinokader.spotiq.util.exception.PartyDoesNotExistException) RetrofitError(retrofit.RetrofitError) Observer(io.reactivex.Observer) SpotifyCommunicatorService(se.zinokader.spotiq.service.SpotifyCommunicatorService) User(se.zinokader.spotiq.model.User) PartyWrongPasswordException(se.zinokader.spotiq.util.exception.PartyWrongPasswordException) Disposable(io.reactivex.disposables.Disposable) PartyWrongPasswordException(se.zinokader.spotiq.util.exception.PartyWrongPasswordException) Party(se.zinokader.spotiq.model.Party) User(se.zinokader.spotiq.model.User) UserPartyInformation(se.zinokader.spotiq.model.UserPartyInformation) PartyDoesNotExistException(se.zinokader.spotiq.util.exception.PartyDoesNotExistException)

Aggregations

Observer (io.reactivex.Observer)18 Observable (io.reactivex.Observable)12 Test (org.junit.Test)9 TestException (io.reactivex.exceptions.TestException)8 TestObserver (io.reactivex.observers.TestObserver)6 ConnectableObservable (io.reactivex.observables.ConnectableObservable)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Bundle (android.os.Bundle)2 Log (android.util.Log)2 AndroidSchedulers (io.reactivex.android.schedulers.AndroidSchedulers)2 Disposable (io.reactivex.disposables.Disposable)2 ObserveOnObserver (io.reactivex.internal.operators.observable.ObservableObserveOn.ObserveOnObserver)2 Schedulers (io.reactivex.schedulers.Schedulers)2 TimeUnit (java.util.concurrent.TimeUnit)2 Inject (javax.inject.Inject)2 UserPrivate (kaaes.spotify.webapi.android.models.UserPrivate)2 Callback (retrofit.Callback)2 RetrofitError (retrofit.RetrofitError)2 Response (retrofit.client.Response)2 ApplicationConstants (se.zinokader.spotiq.constant.ApplicationConstants)2