rx.functions.Action2 Java Examples

The following examples show how to use rx.functions.Action2. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Returns a {@link Transformer} that returns an {@link Observable} that is
 * a buffering of the source Observable into lists of sequential items that
 * satisfy the condition {@code condition}.
 * 
 * <p>
 * <img src=
 * "https://github.com/davidmoten/rxjava-extras/blob/master/src/docs/toListWhile.png?raw=true"
 * alt="marble diagram">
 * 
 * @param condition
 *            condition function that must return true if an item is to be
 *            part of the list being prepared for emission
 * @param <T>
 *            the generic type of the source Observable
 * @return transformer as above
 */
public static <T> Transformer<T, List<T>> toListWhile(
        final Func2<? super List<T>, ? super T, Boolean> condition) {

    Func0<List<T>> initialState = new Func0<List<T>>() {
        @Override
        public List<T> call() {
            return new ArrayList<T>();
        }
    };

    Action2<List<T>, T> collect = new Action2<List<T>, T>() {

        @Override
        public void call(List<T> list, T n) {
            list.add(n);
        }
    };
    return collectWhile(initialState, collect, condition);
}
 
Example #2
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
public static <T> Transformer<T, Set<T>> toSet() {
    return new Transformer<T, Set<T>>() {

        @Override
        public Observable<Set<T>> call(Observable<T> o) {
            return o.collect(new Func0<Set<T>>() {

                @Override
                public Set<T> call() {
                    return new HashSet<T>();
                }
            }, new Action2<Set<T>, T>() {

                @Override
                public void call(Set<T> set, T t) {
                    set.add(t);
                }
            });
        }
    };
}
 
Example #3
Source File: DeviceListAdapter.java    From openwebnet-android with MIT License 6 votes vote down vote up
private void updateEnergyValues(EnergyViewHolder holder, EnergyModel energy) {
    holder.linearLayoutEnergyValues.setVisibility(View.VISIBLE);
    holder.imageViewCardAlert.setVisibility(View.INVISIBLE);

    if (energy.getInstantaneousPower() == null &&
            energy.getDailyPower() == null &&
            energy.getMonthlyPower() == null) {
        log.warn("energy values are null or invalid: unable to update");
        holder.linearLayoutEnergyValues.setVisibility(View.GONE);
        holder.imageViewCardAlert.setVisibility(View.VISIBLE);
        return;
    }

    Action2<TextView, String> updateEnergy = (textView, value) ->
        textView.setText(TextUtils.isEmpty(value) ? utilityService.getString(R.string.energy_none) :
            value + " " + utilityService.getString(R.string.energy_power_unit));

    updateEnergy.call(holder.textViewEnergyInstantaneousPower, energy.getInstantaneousPower());
    updateEnergy.call(holder.textViewEnergyDailyPower, energy.getDailyPower());
    updateEnergy.call(holder.textViewEnergyMonthlyPower, energy.getMonthlyPower());
}
 
Example #4
Source File: FirebaseEntityStore.java    From buddysearch with Apache License 2.0 6 votes vote down vote up
private <T> Observable<T> getQuery(Query query, Action2<Subscriber<? super T>, DataSnapshot> onNextAction, boolean subscribeForSingleEvent) {
    return Observable.create(subscriber -> {
        ValueEventListener eventListener = new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                onNextAction.call(subscriber, dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                subscriber.onError(new FirebaseException(databaseError.getMessage()));
            }
        };
        if (subscribeForSingleEvent) {
            query.addListenerForSingleValueEvent(eventListener);
        } else {
            query.addValueEventListener(eventListener);
        }
        subscriber.add(Subscriptions.create(() -> query.removeEventListener(eventListener)));
    });
}
 
Example #5
Source File: ObservableServerSocket.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
private static Observable<Observable<byte[]>> createServerSocketObservable(
        ServerSocket serverSocket, final long timeoutMs, final int bufferSize,
        final Action0 preAcceptAction, final Func1<? super Socket, Boolean> acceptSocket) {
    return Observable.create( //
            SyncOnSubscribe.<ServerSocket, Observable<byte[]>> createSingleState( //
                    Functions.constant0(serverSocket), //
                    new Action2<ServerSocket, Observer<? super Observable<byte[]>>>() {

                        @Override
                        public void call(ServerSocket ss,
                                Observer<? super Observable<byte[]>> observer) {
                            acceptConnection(timeoutMs, bufferSize, ss, observer,
                                    preAcceptAction, acceptSocket);
                        }
                    }));
}
 
Example #6
Source File: RxPresenter.java    From nucleus with MIT License 5 votes vote down vote up
/**
 * This is a shortcut that can be used instead of combining together
 * {@link #restartable(int, Func0)},
 * {@link #deliverFirst()},
 * {@link #split(Action2, Action2)}.
 *
 * @param restartableId     an id of the restartable.
 * @param observableFactory a factory that should return an Observable when the restartable should run.
 * @param onNext            a callback that will be called when received data should be delivered to view.
 * @param onError           a callback that will be called if the source observable emits onError.
 * @param <T>               the type of the observable.
 */
public <T> void restartableFirst(int restartableId, final Func0<Observable<T>> observableFactory,
    final Action2<View, T> onNext, @Nullable final Action2<View, Throwable> onError) {

    restartable(restartableId, new Func0<Subscription>() {
        @Override
        public Subscription call() {
            return observableFactory.call()
                .compose(RxPresenter.this.<T>deliverFirst())
                .subscribe(split(onNext, onError));
        }
    });
}
 
Example #7
Source File: RxPresenter.java    From nucleus with MIT License 5 votes vote down vote up
/**
 * This is a shortcut that can be used instead of combining together
 * {@link #restartable(int, Func0)},
 * {@link #deliverLatestCache()},
 * {@link #split(Action2, Action2)}.
 *
 * @param restartableId     an id of the restartable.
 * @param observableFactory a factory that should return an Observable when the restartable should run.
 * @param onNext            a callback that will be called when received data should be delivered to view.
 * @param onError           a callback that will be called if the source observable emits onError.
 * @param <T>               the type of the observable.
 */
public <T> void restartableLatestCache(int restartableId, final Func0<Observable<T>> observableFactory,
    final Action2<View, T> onNext, @Nullable final Action2<View, Throwable> onError) {

    restartable(restartableId, new Func0<Subscription>() {
        @Override
        public Subscription call() {
            return observableFactory.call()
                .compose(RxPresenter.this.<T>deliverLatestCache())
                .subscribe(split(onNext, onError));
        }
    });
}
 
Example #8
Source File: EndpointFactoryMock.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Override
public Endpoint create(String hostname, String bucket, String username, String password, int port, CoreContext ctx) {
    final BehaviorSubject<LifecycleState> state = BehaviorSubject.create(LifecycleState.DISCONNECTED);
    final Endpoint endpoint = mock(Endpoint.class);
    when(endpoint.states()).thenReturn(state);
    for (Action2<Endpoint, BehaviorSubject<LifecycleState>> action : createActions) {
        action.call(endpoint, state);
    }

    endpoints.add(endpoint);
    endpointStates.add(state);
    return endpoint;
}
 
Example #9
Source File: DeliveryTest.java    From FlowGeek with GNU General Public License v2.0 5 votes vote down vote up
private void testWithOnNextOnError(Action2<Action2, Action2> test) {
    Action2 onNext = mock(Action2.class);
    Action2 onError = mock(Action2.class);

    test.call(onNext, onError);

    verifyNoMoreInteractions(onNext);
    verifyNoMoreInteractions(onError);
}
 
Example #10
Source File: DeliveryTest.java    From FlowGeek with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSplitOnNext() throws Exception {
    testWithOnNextOnError(new Action2<Action2, Action2>() {
        @Override
        public void call(Action2 onNext, Action2 onError) {
            new Delivery(1, Notification.createOnNext(2)).split(onNext, onError);
            verify(onNext, times(1)).call(1, 2);
        }
    });
}
 
Example #11
Source File: DeliveryTest.java    From FlowGeek with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSplitOnError() throws Exception {
    testWithOnNextOnError(new Action2<Action2, Action2>() {
        @Override
        public void call(Action2 onNext, Action2 onError) {
            Throwable throwable = new Throwable();
            new Delivery(1, Notification.createOnError(throwable)).split(onNext, onError);
            verify(onError, times(1)).call(1, throwable);
        }
    });
}
 
Example #12
Source File: DeliveryTest.java    From FlowGeek with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSplitOnComplete() throws Exception {
    testWithOnNextOnError(new Action2<Action2, Action2>() {
        @Override
        public void call(Action2 onNext, Action2 onError) {
            new Delivery(1, Notification.createOnCompleted()).split(onNext, onError);
        }
    });
}
 
Example #13
Source File: PooledServiceTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotCreateNewEndpointOrAcceptRequestIfNodeIsDown() {
    EndpointFactoryMock ef = EndpointFactoryMock.simple(envCtx);
    ef.onCreate(new Action2<Endpoint, BehaviorSubject<LifecycleState>>() {
        @Override
        public void call(final Endpoint endpoint, final BehaviorSubject<LifecycleState> states) {
            when(endpoint.connect()).then(new Answer<Observable<LifecycleState>>() {
                @Override
                public Observable<LifecycleState> answer(InvocationOnMock invocation) throws Throwable {
                    states.onNext(LifecycleState.DISCONNECTING);
                    return Observable.error(new ConnectException("could not connect to remote"));
                }
            });
        }
    });

    SelectionStrategy ss = new RoundRobinSelectionStrategy();
    MockedService ms = new MockedService(ServiceType.QUERY, ef, ssc(0, 1), ss);
    ms.connect().toBlocking().single();

    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr1 = mockRequest();

    ms.send(mr1.value1());
    ef.advanceAll(LifecycleState.CONNECTED);

    assertEquals(1, ef.endpointCount());

    mr1.value2().assertError(RequestCancelledException.class);

    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr2 = mockRequest();
    ms.send(mr2.value1());

    // Second request should not create another endpoint
    assertEquals(1, ef.endpointCount());
    assertEquals(0, ef.endpointSendCalled());

    mr1.value2().assertError(RequestCancelledException.class);
}
 
Example #14
Source File: ExternalChildResourceCollectionImpl.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Commits the changes in the external child resource childCollection.
 * <p/>
 * This method returns a observable stream, either its observer's onError will be called with
 * {@link CompositeException} if some resources failed to commit or onNext will be called if all resources
 * committed successfully.
 *
 * @return the observable stream
 */
public Observable<List<FluentModelTImpl>> commitAndGetAllAsync() {
    return commitAsync().collect(
            new Func0<List<FluentModelTImpl>>() {
                public List<FluentModelTImpl> call() {
                    return new ArrayList<>();
                }
            },
            new Action2<List<FluentModelTImpl>, FluentModelTImpl>() {
                public void call(List<FluentModelTImpl> state, FluentModelTImpl item) {
                    state.add(item);
                }
            });
}
 
Example #15
Source File: TabListAdapter.java    From photosearcher with Apache License 2.0 5 votes vote down vote up
public TabListAdapter(ITabDataSetManager<String> tabDataSetManager,
                      OnStartViewHolderDragListener dragStartListener,
                      Action1<String> onDeleteQuery,
                      Action2<Integer, Integer> onMoveItem,
                      Action1<String> onItemClick) {
    mTabDataSetManager = tabDataSetManager;
    mDragStartListener = dragStartListener;
    mOnDeleteQuery = onDeleteQuery;
    mOnMoveItem = onMoveItem;
    mOnItemClick = onItemClick;
}
 
Example #16
Source File: PooledServiceTest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRetryWhenSocketOpenFailedOnSend() {
    EndpointFactoryMock ef = EndpointFactoryMock.simple(envCtx);
    ef.onCreate(new Action2<Endpoint, BehaviorSubject<LifecycleState>>() {
        @Override
        public void call(final Endpoint endpoint, final BehaviorSubject<LifecycleState> states) {
            when(endpoint.connect()).then(new Answer<Observable<LifecycleState>>() {
                @Override
                public Observable<LifecycleState> answer(InvocationOnMock invocation) throws Throwable {
                    states.onNext(LifecycleState.DISCONNECTED);
                    return Observable.error(new Exception("something happened"));
                }
            });
        }
    });

    SelectionStrategy ss = mock(SelectionStrategy.class);

    MockedService ms = new MockedService(ServiceType.QUERY, ef, ssc(0, 2), ss);
    ms.connect().toBlocking().single();

    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr1 = mockRequest();
    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr2 = mockRequest();
    Tuple2<CouchbaseRequest, TestSubscriber<CouchbaseResponse>> mr3 = mockRequest();

    when(ss.select(any(CouchbaseRequest.class), any(List.class))).thenReturn(null);
    ms.send(mr1.value1());
    ms.send(mr2.value1());
    ms.send(mr3.value1());

    assertEquals(0, ef.endpointSendCalled());

    mr1.value2().assertError(RequestCancelledException.class);
    mr2.value2().assertError(RequestCancelledException.class);
    mr3.value2().assertError(RequestCancelledException.class);
}
 
Example #17
Source File: Checked.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T,R> Action2<T, R> a2(final A2<T, R> a) {
    return new Action2<T, R>() {
        @Override
        public void call(T t, R r) {
            try {
                a.call(t, r);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
}
 
Example #18
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T, R extends Iterable<?>> Transformer<T, R> collectWhile(final Func0<R> factory,
        final Action2<? super R, ? super T> collect,
        final Func2<? super R, ? super T, Boolean> condition) {
    Func1<R, Boolean> isEmpty = new Func1<R, Boolean>() {
        @Override
        public Boolean call(R collection) {
            return !collection.iterator().hasNext();
        }
    };
    return collectWhile(factory, collect, condition, isEmpty);
}
 
Example #19
Source File: EndpointFactoryMock.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
public void onDisconnectTransition(final Func1<Endpoint, LifecycleState> action) {
    onCreate(new Action2<Endpoint, BehaviorSubject<LifecycleState>>() {
        @Override
        public void call(final Endpoint endpoint, final BehaviorSubject<LifecycleState> states) {
            when(endpoint.disconnect()).then(new Answer<Observable<LifecycleState>>() {
                @Override
                public Observable<LifecycleState> answer(InvocationOnMock invocation) throws Throwable {
                    LifecycleState state = action.call(endpoint);
                    states.onNext(state);
                    return Observable.just(state);
                }
            });
        }
    });
}
 
Example #20
Source File: RxPresenter.java    From nucleus with MIT License 5 votes vote down vote up
/**
 * This is a shortcut that can be used instead of combining together
 * {@link #restartable(int, Func0)},
 * {@link #deliverReplay()},
 * {@link #split(Action2, Action2)}.
 *
 * @param restartableId     an id of the restartable.
 * @param observableFactory a factory that should return an Observable when the restartable should run.
 * @param onNext            a callback that will be called when received data should be delivered to view.
 * @param onError           a callback that will be called if the source observable emits onError.
 * @param <T>               the type of the observable.
 */
public <T> void restartableReplay(int restartableId, final Func0<Observable<T>> observableFactory,
    final Action2<View, T> onNext, @Nullable final Action2<View, Throwable> onError) {

    restartable(restartableId, new Func0<Subscription>() {
        @Override
        public Subscription call() {
            return observableFactory.call()
                .compose(RxPresenter.this.<T>deliverReplay())
                .subscribe(split(onNext, onError));
        }
    });
}
 
Example #21
Source File: RxPresenter.java    From FlowGeek with GNU General Public License v2.0 5 votes vote down vote up
public <T, T1, T2, T3, T4> void restartableFirst(int restartableId,
                                                 final Func4<T1, T2, T3, T4, Observable<T>> observableFactory,
                                                 final Action2<View, T> onNext,
                                                 @Nullable final Action2<View, Throwable> onError) {

    restartable(restartableId, new Func4<T1, T2, T3, T4, Subscription>() {
        @Override
        public Subscription call(T1 arg1, T2 arg2, T3 arg3, T4 arg4) {
            return observableFactory.call(arg1, arg2, arg3, arg4)
                    .compose(RxPresenter.this.<T>deliverFirst())
                    .subscribe(split(onNext, onError));
        }
    });
}
 
Example #22
Source File: EndpointFactoryMock.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
EndpointFactoryMock(String hostname, String bucket, String password, int port, CoreContext ctx) {
    this.hostname = hostname;
    this.bucket = bucket;
    this.password = password;
    this.port = port;
    this.ctx = ctx;
    this.env = ctx.environment();
    this.responseBuffer = ctx.responseRingBuffer();
    this.endpoints = Collections.synchronizedList(new ArrayList<Endpoint>());
    this.endpointStates = Collections.synchronizedList(new ArrayList<BehaviorSubject<LifecycleState>>());
    this.createActions = Collections.synchronizedList(
        new ArrayList<Action2<Endpoint, BehaviorSubject<LifecycleState>>>()
    );
}
 
Example #23
Source File: DeliveryTest.java    From nucleus with MIT License 5 votes vote down vote up
private void testWithOnNextOnError(Action2<Action2, Action2> test) {
    Action2 onNext = mock(Action2.class);
    Action2 onError = mock(Action2.class);

    test.call(onNext, onError);

    verifyNoMoreInteractions(onNext);
    verifyNoMoreInteractions(onError);
}
 
Example #24
Source File: DeliveryTest.java    From nucleus with MIT License 5 votes vote down vote up
@Test
public void testSplitOnNext() throws Exception {
    testWithOnNextOnError(new Action2<Action2, Action2>() {
        @Override
        public void call(Action2 onNext, Action2 onError) {
            new Delivery(1, Notification.createOnNext(2)).split(onNext, onError);
            verify(onNext, times(1)).call(1, 2);
        }
    });
}
 
Example #25
Source File: AwsObservableExt.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public <REQ extends AmazonWebServiceRequest, RES> AsyncHandler<REQ, RES> handler(Action2<REQ, RES> onSuccessAction, Action1<Exception> onErrorAction) {
    return new AsyncHandler<REQ, RES>() {
        @Override
        public void onError(Exception exception) {
            onErrorAction.call(exception);
            subscriber.onError(exception);
        }

        @Override
        public void onSuccess(REQ request, RES result) {
            onSuccessAction.call(request, result);
            subscriber.onCompleted();
        }
    };
}
 
Example #26
Source File: VirtualMachineExtensionsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * @return an observable emits extensions in this collection as a map indexed by name.
 */
public Observable<Map<String, VirtualMachineExtension>> asMapAsync() {
    return listAsync()
            .collect(new Func0<Map<String, VirtualMachineExtension>>() {
                @Override
                public Map<String, VirtualMachineExtension> call() {
                    return new HashMap<>();
                }
            }, new Action2<Map<String, VirtualMachineExtension>, VirtualMachineExtension>() {
                @Override
                public void call(Map<String, VirtualMachineExtension> map, VirtualMachineExtension extension) {
                    map.put(extension.name(), extension);
                }
            });
}
 
Example #27
Source File: ExternalChildResourceCollectionImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Commits the changes in the external child resource childCollection.
 * <p/>
 * This method returns a observable stream, either its observer's onError will be called with
 * {@link CompositeException} if some resources failed to commit or onNext will be called if all resources
 * committed successfully.
 *
 * @return the observable stream
 */
public Observable<List<FluentModelTImpl>> commitAndGetAllAsync() {
    return commitAsync().collect(
            new Func0<List<FluentModelTImpl>>() {
                public List<FluentModelTImpl> call() {
                    return new ArrayList<>();
                }
            },
            new Action2<List<FluentModelTImpl>, FluentModelTImpl>() {
                public void call(List<FluentModelTImpl> state, FluentModelTImpl item) {
                    state.add(item);
                }
            });
}
 
Example #28
Source File: DeliveryTest.java    From nucleus with MIT License 5 votes vote down vote up
@Test
public void testSplitOnError() throws Exception {
    testWithOnNextOnError(new Action2<Action2, Action2>() {
        @Override
        public void call(Action2 onNext, Action2 onError) {
            Throwable throwable = new Throwable();
            new Delivery(1, Notification.createOnError(throwable)).split(onNext, onError);
            verify(onError, times(1)).call(1, throwable);
        }
    });
}
 
Example #29
Source File: DeliveryTest.java    From nucleus with MIT License 5 votes vote down vote up
@Test
public void testSplitOnComplete() throws Exception {
    testWithOnNextOnError(new Action2<Action2, Action2>() {
        @Override
        public void call(Action2 onNext, Action2 onError) {
            new Delivery(1, Notification.createOnCompleted()).split(onNext, onError);
        }
    });
}
 
Example #30
Source File: EndpointFactoryMock.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
public void onConnectTransition(final Func1<Endpoint, LifecycleState> action) {
    onCreate(new Action2<Endpoint, BehaviorSubject<LifecycleState>>() {
        @Override
        public void call(final Endpoint endpoint, final BehaviorSubject<LifecycleState> states) {
            when(endpoint.connect()).then(new Answer<Observable<LifecycleState>>() {
                @Override
                public Observable<LifecycleState> answer(InvocationOnMock invocation) throws Throwable {
                    LifecycleState state = action.call(endpoint);
                    states.onNext(state);
                    return Observable.just(state);
                }
            });
        }
    });
}