rx.functions.Action0 Java Examples

The following examples show how to use rx.functions.Action0. 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: Chest.java    From Iron with Apache License 2.0 6 votes vote down vote up
public <T> Observable<T> get(final String key) {
    return Observable.create(new Observable.OnSubscribe<T>() {
        @Override
        public void call(final Subscriber<? super T> subscriber) {
            final DataChangeCallback<T> callback = new DataChangeCallback<T>(key) {
                @Override
                public void onDataChange(T value) {
                    if (!subscriber.isUnsubscribed()) {
                        subscriber.onNext(value);
                    }
                }
            };
            Chest.this.addOnDataChangeListener(callback);
            subscriber.add(Subscriptions.create(new Action0() {
                @Override
                public void call() {
                    Chest.this.removeListener(callback);
                }
            }));
            subscriber.onNext(Chest.this.<T>read(key));
        }
    }).compose(this.<T>applySchedulers());
}
 
Example #2
Source File: Example6.java    From AnDevCon-RxPatterns with Apache License 2.0 6 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();

    resumeSub = exampleObservable
            .doOnUnsubscribe(new Action0() {
                @Override
                public void call() {
                    Log.d(TAG, "Called unsubscribe OnPause()");
                }
            })
            .subscribe(new Action1<Integer>() {
                @Override
                public void call(Integer i) {
                    mOutputTextView3.setText(Integer.toString(i) + " OnResume()");
                }
            }, errorHandler);
}
 
Example #3
Source File: DatabaseTestBase.java    From rxjava-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testTwoConnectionsOpenedAndClosedWhenTakeOneUsedWithSelectThatReturnsOneRow()
        throws InterruptedException {
    Action0 completed = new Action0() {

        @Override
        public void call() {
            System.out.println("completed");
        }
    };
    CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1);
    Database db = new Database(cp);
    db.select("select count(*) from person").getAs(Long.class).doOnCompleted(completed).take(1)
            .toBlocking().single();
    assertTrue(cp.getsLatch().await(6, TimeUnit.SECONDS));
    assertTrue(cp.closesLatch().await(6, TimeUnit.SECONDS));
}
 
Example #4
Source File: Obs.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
private static <T> void startScheduledResetAgain(final long duration, final TimeUnit unit,
        final Scheduler scheduler, final AtomicReference<CachedObservable<T>> cacheRef,
        final AtomicReference<Optional<Worker>> workerRef) {

    Action0 action = new Action0() {
        @Override
        public void call() {
            cacheRef.get().reset();
        }
    };
    // CAS loop to cancel the current worker and create a new one
    while (true) {
        Optional<Worker> wOld = workerRef.get();
        if (wOld == null) {
            // we are finished
            return;
        }
        Optional<Worker> w = Optional.of(scheduler.createWorker());
        if (workerRef.compareAndSet(wOld, w)) {
            if (wOld.isPresent())
                wOld.get().unsubscribe();
            w.get().schedule(action, duration, unit);
            break;
        }
    }
}
 
Example #5
Source File: Transformers.java    From mobius with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link Transformer} that will flatten the provided {@link Action0} into the stream
 * as a {@link Completable} every time it receives an effect from the upstream effects observable.
 * This Completable will be subscribed on the specified {@link Scheduler}. This will result in
 * calling the provided Action on the specified scheduler every time an effect dispatched to the
 * created effect transformer.
 *
 * @param doEffect {@link Action0} to be run every time the effect is requested
 * @param scheduler the {@link Scheduler} that the action should be run on
 * @param <F> the type of Effect this transformer handles
 * @param <E> these transformers are for effects that do not result in any events; however, they
 *     still need to share the same Event type
 * @return a {@link Transformer} that can be used with an {@link SubtypeEffectHandlerBuilder}
 */
static <F, E> Transformer<F, E> fromAction(
    final Action0 doEffect, @Nullable final Scheduler scheduler) {
  return fromConsumer(
      new Action1<F>() {
        @Override
        public void call(F f) {
          try {
            doEffect.call();
          } catch (Exception e) {
            throw OnErrorThrowable.from(e);
          }
        }
      },
      scheduler);
}
 
Example #6
Source File: PushServers.java    From mantis with Apache License 2.0 6 votes vote down vote up
public static <K, V> LegacyTcpPushServer<KeyValuePair<K, V>> infiniteStreamLegacyTcpNestedMantisGroup(ServerConfig<KeyValuePair<K, V>> config,
                                                                                                      Observable<Observable<MantisGroup<K, V>>> go,
                                                                                                      long groupExpirySeconds, final Func1<K, byte[]> keyEncoder,
                                                                                                      HashFunction hashFunction) {
    final PublishSubject<String> serverSignals = PublishSubject.create();
    final String serverName = config.getName();
    Action0 onComplete = new Action0() {
        @Override
        public void call() {
            serverSignals.onNext("ILLEGAL_STATE_COMPLETED");
            throw new IllegalStateException("OnComplete signal received, Server: " + serverName + " is pushing an infinite stream, should not complete");
        }
    };

    Action1<Throwable> onError = new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            serverSignals.onError(t);
        }
    };

    PushTrigger<KeyValuePair<K, V>> trigger = ObservableTrigger.oomgo(serverName, go, onComplete, onError, groupExpirySeconds,
            keyEncoder, hashFunction);
    return new LegacyTcpPushServer<KeyValuePair<K, V>>(trigger, config, serverSignals);
}
 
Example #7
Source File: BroadcastObservable.java    From RxSerach with Apache License 2.0 6 votes vote down vote up
private static Subscription unsubscribeInUiThread(final Action0 unsubscribe) {
    return Subscriptions.create(new Action0() {
        @Override public void call() {
            if (Looper.getMainLooper() == Looper.myLooper()) {
                unsubscribe.call();
            } else {
                final Scheduler.Worker inner = AndroidSchedulers.mainThread().createWorker();
                inner.schedule(new Action0() {
                    @Override public void call() {
                        unsubscribe.call();
                        inner.unsubscribe();
                    }
                });
            }
        }
    });
}
 
Example #8
Source File: SecretImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public Observable<Secret> updateResourceAsync() {
    Observable<Secret> set = Observable.just((Secret) this);
    if (setSecretRequest != null) {
        set = createResourceAsync();
    }
    return set.flatMap(new Func1<Secret, Observable<SecretBundle>>() {
        @Override
        public Observable<SecretBundle> call(Secret secret) {
            return Observable.from(vault.client().updateSecretAsync(updateSecretRequest.build(), null));
        }
    }).flatMap(new Func1<SecretBundle, Observable<Secret>>() {
        @Override
        public Observable<Secret> call(SecretBundle secretBundle) {
            return refreshAsync();
        }
    }).doOnCompleted(new Action0() {
        @Override
        public void call() {
            setSecretRequest = null;
            updateSecretRequest = new UpdateSecretRequest.Builder(vault.vaultUri(), name());
        }
    });
}
 
Example #9
Source File: InstrumentedEventLoop.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private Action0 instrumentedAction(String actionName, Action0 action) {
    return () -> {
        ActionMetrics actionMetrics = this.actionMetrics.computeIfAbsent(actionName, k -> {
            String rootName = metricNameRoot + ".eventLoop." + actionName;
            return SpectatorExt.actionMetrics(rootName, Collections.emptyList(), registry);
        });
        long start = actionMetrics.start();
        try {
            action.call();
            actionMetrics.success();
        } catch (Exception e) {
            actionMetrics.failure(e);
        } finally {
            actionMetrics.finish(start);
            actionsRemaining.decrementAndGet();
        }
    };
}
 
Example #10
Source File: EVCacheOperationFuture.java    From EVCache with Apache License 2.0 6 votes vote down vote up
public Single<T> get(long duration, TimeUnit units, boolean throwException, boolean hasZF, Scheduler scheduler) {
    return observe().timeout(duration, units, Single.create(subscriber -> {
        // whenever timeout occurs, continuous timeout counter will increase by 1.
        MemcachedConnection.opTimedOut(op);
        if (op != null) op.timeOut();
        //if (!hasZF) EVCacheMetricsFactory.getCounter(appName, null, serverGroup.getName(), appName + "-get-CheckedOperationTimeout", DataSourceType.COUNTER).increment();
        if (throwException) {
            subscriber.onError(new CheckedOperationTimeoutException("Timed out waiting for operation", op));
        } else {
            if (isCancelled()) {
                //if (hasZF) EVCacheMetricsFactory.getCounter(appName, null, serverGroup.getName(), appName + "-get-Cancelled", DataSourceType.COUNTER).increment();
            }
            subscriber.onSuccess(objRef.get());
        }
    }), scheduler).doAfterTerminate(new Action0() {
        @Override
        public void call() {

        }
    }
    );
}
 
Example #11
Source File: RequestProcessor.java    From mantis with Apache License 2.0 6 votes vote down vote up
public Observable<Void> sendInfiniteStream(final HttpServerResponse<ByteBuf> response) {
    response.getHeaders().add(HttpHeaders.Names.CONTENT_TYPE, "text/event-stream");
    response.getHeaders().add(HttpHeaders.Names.TRANSFER_ENCODING, "chunked");

    return Observable.create(new OnSubscribe<Void>() {
        final AtomicLong counter = new AtomicLong();
        Worker worker = Schedulers.computation().createWorker();

        public void call(Subscriber<? super Void> subscriber) {
            worker.schedulePeriodically(
                    new Action0() {
                        @Override
                        public void call() {
                            System.out.println("In infinte stream");
                            byte[] contentBytes = ("data:" + "line " + counter.getAndIncrement() + "\n\n").getBytes();
                            response.writeBytes(contentBytes);
                            response.flush();
                        }
                    },
                    0,
                    100,
                    TimeUnit.MILLISECONDS
            );
        }
    });
}
 
Example #12
Source File: DynamicConnectionSet.java    From mantis with Apache License 2.0 6 votes vote down vote up
public static <K, V> DynamicConnectionSet<MantisGroup<K, V>> createMGO(
        final ConnectToGroupedObservable.Builder<K, V> config, int maxTimeBeforeDisconnectSec, final SpscArrayQueue<MantisGroup<?, ?>> inputQueue) {
    Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<MantisGroup<K, V>>> toObservableFunc
            = new Func3<Endpoint, Action0, PublishSubject<Integer>, RemoteRxConnection<MantisGroup<K, V>>>() {
        @Override
        public RemoteRxConnection<MantisGroup<K, V>> call(Endpoint endpoint, Action0 disconnectCallback,
                                                          PublishSubject<Integer> closeConnectionTrigger) {
            // copy config, change host, port and id
            ConnectToGroupedObservable.Builder<K, V> configCopy = new ConnectToGroupedObservable.Builder<K, V>(config);
            configCopy
                    .host(endpoint.getHost())
                    .port(endpoint.getPort())
                    .closeTrigger(closeConnectionTrigger)
                    .connectionDisconnectCallback(disconnectCallback)
                    .slotId(endpoint.getSlotId());
            return RemoteObservable.connectToMGO(configCopy.build(), inputQueue);
        }
    };
    return new DynamicConnectionSet<MantisGroup<K, V>>(toObservableFunc, MIN_TIME_SEC_DEFAULT, maxTimeBeforeDisconnectSec);
}
 
Example #13
Source File: PrayerManager.java    From android with Apache License 2.0 6 votes vote down vote up
private Observable<PrayerContext> updatePrayerContext(String code) {
    Timber.i("Updating preferred prayer context");

    return mPrayerDownloader.getPrayerTimes(code)
            .doOnNext(new Action1<PrayerContext>() {
                @Override
                public void call(PrayerContext prayerContext) {
                    mLastPrayerContext = prayerContext;
                    broadcastPrayerContext(prayerContext);
                }
            })
            .doOnSubscribe(new Action0() {
                @Override
                public void call() {
                    mIsLoading.set(true);
                }
            })
            .doOnTerminate(new Action0() {
                @Override
                public void call() {
                    mIsLoading.set(false);
                }
            });
}
 
Example #14
Source File: PushServers.java    From mantis with Apache License 2.0 6 votes vote down vote up
public static <K, V> LegacyTcpPushServer<KeyValuePair<K, V>> infiniteStreamLegacyTcpNestedGroupedObservable(ServerConfig<KeyValuePair<K, V>> config,
                                                                                                            Observable<Observable<GroupedObservable<K, V>>> go,
                                                                                                            long groupExpirySeconds, final Func1<K, byte[]> keyEncoder,
                                                                                                            HashFunction hashFunction) {
    final PublishSubject<String> serverSignals = PublishSubject.create();
    final String serverName = config.getName();
    Action0 onComplete = new Action0() {
        @Override
        public void call() {
            serverSignals.onNext("ILLEGAL_STATE_COMPLETED");
            throw new IllegalStateException("OnComplete signal received, Server: " + serverName + " is pushing an infinite stream, should not complete");
        }
    };

    Action1<Throwable> onError = new Action1<Throwable>() {
        @Override
        public void call(Throwable t) {
            serverSignals.onError(t);
        }
    };

    PushTrigger<KeyValuePair<K, V>> trigger = ObservableTrigger.oogo(serverName, go, onComplete, onError, groupExpirySeconds,
            keyEncoder, hashFunction);
    return new LegacyTcpPushServer<KeyValuePair<K, V>>(trigger, config, serverSignals);
}
 
Example #15
Source File: EndlessRecyclerOnScrollListener.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
public <T extends BaseV7EndlessResponse> EndlessRecyclerOnScrollListener(BaseAdapter baseAdapter,
    V7<T, ? extends Endless> v7request, Action1<T> successRequestListener,
    ErrorRequestListener errorRequestListener, int visibleThreshold, boolean bypassCache,
    BooleanAction<T> onFirstLoadListener, Action0 onEndOfListReachedListener) {
  this.multiLangPatch = new MultiLangPatch();
  this.onEndlessFinishList = new LinkedList<>();
  this.adapter = baseAdapter;
  this.v7request = v7request;
  this.successRequestListener = successRequestListener;
  this.errorRequestListener = errorRequestListener;
  this.visibleThreshold = visibleThreshold;
  this.bypassCache = bypassCache;
  this.onFirstLoadListener = onFirstLoadListener;
  this.onEndOfListReachedListener = onEndOfListReachedListener;
  this.endCallbackCalled = false;
  this.firstCallbackCalled = false;
  bypassServerCache = false;
}
 
Example #16
Source File: PrayerManager.java    From android with Apache License 2.0 5 votes vote down vote up
private Observable<PrayerContext> getPreferredPrayerContext(boolean refresh) {
    final PrayerCode location = mLocationPreferences.getPreferredLocation();

    if (location == null) {
        return getAutomaticPrayerContext(refresh);
    }

    return Observable.just(location.getCode())
            .doOnSubscribe(new Action0() {
                @Override
                public void call() {
                    mIsError.set(false);
                }
            })
            .flatMap(new Func1<String, Observable<PrayerContext>>() {
                @Override
                public Observable<PrayerContext> call(String code) {
                    if (shouldUpdatePrayerContext(code) && !isLoading()) {
                        mLastPreferredLocation = location;
                        return updatePrayerContext(code);
                    }

                    if (mLastPrayerContext != null) {
                        return Observable.just(mLastPrayerContext);
                    } else {
                        return mPrayerStream.asObservable()
                                .first();
                    }
                }
            });
}
 
Example #17
Source File: DeviceListAdapter.java    From openwebnet-android with MIT License 5 votes vote down vote up
private void sendScenarioRequestStop(ScenarioViewHolder holder, ScenarioModel scenario) {
    log.debug("stop scenario {}", scenario.getUuid());
    if (scenario.getStatus() == null) {
        log.warn("scenario status is null: unable to stop");
        return;
    }

    Action0 updateScenarioStatusAction = () -> updateScenarioStatus(holder, scenario.getStatus(), scenario.isEnable());
    scenarioService.stop(scenario).doOnCompleted(updateScenarioStatusAction).subscribe();
}
 
Example #18
Source File: GetUsersTest.java    From buddysearch with Apache License 2.0 5 votes vote down vote up
@Test
@Override
public void testBuildUseCaseObservable() {
    testBuildUseCaseObservable(null, new Action0() {
        @Override
        public void call() {
            verify(mockRepository).getUsers(mockMessenger);
        }
    });
}
 
Example #19
Source File: NativeExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void actionsToHandler() {
  Action1<HttpServer> onNext = httpServer -> {};
  Action1<Throwable> onError = httpServer -> {};
  Action0 onComplete = () -> {};

  Handler<AsyncResult<HttpServer>> handler1 = RxHelper.toFuture(onNext);
  Handler<AsyncResult<HttpServer>> handler2 = RxHelper.toFuture(onNext, onError);
  Handler<AsyncResult<HttpServer>> handler3 = RxHelper.toFuture(onNext, onError, onComplete);
}
 
Example #20
Source File: BindingAdapters.java    From android-mvvm with Apache License 2.0 5 votes vote down vote up
@BindingConversion
public static View.OnClickListener toOnClickListener(final Action0 listener) {
    if (listener != null) {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.call();
            }
        };
    } else {
        return null;
    }
}
 
Example #21
Source File: LocalJobExecutorNetworked.java    From mantis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings( {"rawtypes", "unchecked"})
private static void startSink(StageConfig previousStage, int[] previousStagePorts, StageConfig stage, PortSelector portSelector,
                              SinkHolder sink, Context context,
                              Action0 sinkObservableCompletedCallback,
                              Action0 sinkObservableTerminatedCompletedCallback,
                              Action1<Throwable> sinkObservableErrorCallback,
                              int stageNumber,
                              int workerIndex,
                              int workersAtPreviousStage) {
    if (logger.isDebugEnabled()) {
        StringBuilder portsToString = new StringBuilder();
        for (int previousPort : previousStagePorts) {
            portsToString.append(previousPort + " ");
        }
        logger.debug("Creating sink consumer connecting to publishers on ports " + portsToString);
    }

    Observable<Set<Endpoint>> endpoints = staticEndpoints(previousStagePorts, stageNumber, workerIndex, numPartitions);
    WorkerConsumerRemoteObservable sinkConsumer
            = new WorkerConsumerRemoteObservable(null, // name=null for local
            staticInjector(endpoints));

    StageExecutors.executeSink(sinkConsumer, stage, sink, portSelector,
            new RxMetrics(), context, sinkObservableTerminatedCompletedCallback,
            null, null,
            sinkObservableCompletedCallback, sinkObservableErrorCallback);
}
 
Example #22
Source File: SingleThreadedComputationScheduler.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) {
    if (innerSubscription.isUnsubscribed()) {
        // don't schedule, we are unsubscribed
        return Subscriptions.empty();
    }
    
    ScheduledAction s = (ScheduledAction)innerWorker.schedule(action, delayTime, unit);
    innerSubscription.add(s);
    s.addParent(innerSubscription);
    return s;
}
 
Example #23
Source File: WaitingForReconnectState.java    From jawampa with Apache License 2.0 5 votes vote down vote up
@Override
public void onEnter(ClientState lastState) {
    reconnectSubscription =
        stateController.rxScheduler().createWorker().schedule(new Action0() {
            @Override
            public void call() {
                if (stateController.currentState() != WaitingForReconnectState.this) return;
                // Reconnect now
                ConnectingState newState = new ConnectingState(stateController, nrReconnectAttempts);
                stateController.setState(newState);
            }
        }, stateController.clientConfig().reconnectInterval(), TimeUnit.MILLISECONDS);
}
 
Example #24
Source File: Actions.java    From ocelli with Apache License 2.0 5 votes vote down vote up
public static Action0 once(final Action0 delegate) {
    return new Action0() {
        private AtomicBoolean called = new AtomicBoolean(false);
        @Override
        public void call() {
            if (called.compareAndSet(false, true)) {
                delegate.call();
            }
        }
    };
}
 
Example #25
Source File: UserPresenter.java    From GithubApp with Apache License 2.0 5 votes vote down vote up
public void getSingleUser(String name) {
    mCompositeSubscription.add(mRepoApi.getSingleUser(name)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe(new Action0() {
                @Override
                public void call() {
                    getMvpView().showLoading();
                }
            })
            .doOnTerminate(new Action0() {
                @Override
                public void call() {
                    getMvpView().dismissLoading();
                }
            })
            .subscribe(new ResponseObserver<User>() {

                @Override
                public void onError(Throwable e) {
                    getMvpView().showError(e);
                }

                @Override
                public void onSuccess(User user) {
                    getMvpView().showContent(user);
                }
            }));
}
 
Example #26
Source File: ProfileActivity.java    From openwebnet-android with MIT License 5 votes vote down vote up
private void showConfirmationDialog(int titleStringId, int messageStringId, Action0 actionOk) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle(titleStringId)
        .setMessage(messageStringId)
        .setPositiveButton(android.R.string.ok, null)
        .setNeutralButton(android.R.string.cancel, null);

    AlertDialog dialog = builder.create();
    dialog.show();
    dialog.getButton(AlertDialog.BUTTON_POSITIVE)
        .setOnClickListener(v -> {
            actionOk.call();
            dialog.dismiss();
        });
}
 
Example #27
Source File: Context.java    From mantis with Apache License 2.0 5 votes vote down vote up
public Context(Parameters parameters, ServiceLocator serviceLocator, WorkerInfo workerInfo,
               MetricsRegistry metricsRegistry, Action0 completeAndExitAction, Observable<WorkerMap> workerMapObservable) {
    this.parameters = parameters;
    this.serviceLocator = serviceLocator;
    this.workerInfo = workerInfo;
    this.metricsRegistry = metricsRegistry;
    if (completeAndExitAction == null)
        throw new IllegalArgumentException("Null complete action provided in Context contructor");
    this.completeAndExitAction = completeAndExitAction;
    this.workerMapObservable = workerMapObservable;
}
 
Example #28
Source File: GoogleSearchController.java    From FloatingSearchView with Apache License 2.0 5 votes vote down vote up
private void notifyStarted(final String query) {
    if(mListener == null) return;
    dispatchOnMainThread(new Action0() {
        @Override
        public void call() {
            mListener.onSearchStarted(query);
        }
    });
}
 
Example #29
Source File: QuerySelectOnSubscribe.java    From rxjava-jdbc with Apache License 2.0 5 votes vote down vote up
private static <T> void setupUnsubscription(Subscriber<T> subscriber, final State state) {
    subscriber.add(Subscriptions.create(new Action0() {
        @Override
        public void call() {
            closeQuietly(state);
        }
    }));
}
 
Example #30
Source File: MainThreadSubscription.java    From letv with Apache License 2.0 5 votes vote down vote up
public final void unsubscribe() {
    if (!this.unsubscribed.compareAndSet(false, true)) {
        return;
    }
    if (Looper.myLooper() == Looper.getMainLooper()) {
        onUnsubscribe();
    } else {
        AndroidSchedulers.mainThread().createWorker().schedule(new Action0() {
            public void call() {
                MainThreadSubscription.this.onUnsubscribe();
            }
        });
    }
}