rx.functions.Func0 Java Examples

The following examples show how to use rx.functions.Func0. 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: RxPresenterTest.java    From FlowGeek with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testCompletedRestartable() throws Exception {
    Func0<Subscription> restartable = mock(Func0.class);
    Subscription subscription = mock(Subscription.class);

    RxPresenter presenter = new RxPresenter();
    presenter.create(null);

    when(restartable.call()).thenReturn(subscription);
    when(subscription.isUnsubscribed()).thenReturn(true);
    presenter.restartable(1, restartable);

    verifyNoMoreInteractions(restartable);

    presenter.start(1);
}
 
Example #2
Source File: Restartable.java    From satellite with MIT License 6 votes vote down vote up
/**
 * Provides a channel to an observable that can be created with a given observable factory.
 *
 * Note that to make use of arguments, both
 * {@link #channel(DeliveryMethod, ObservableFactory)} and
 * {@link #launch(Object)} variants should be used.
 *
 * @param type              a type of the channel.
 * @param observableFactory an observable factory which will be used to create an observable per launch.
 * @return an observable which emits {@link rx.Notification} of onNext and onError observable emissions.
 */
public <A, T> Observable<Notification<T>> channel(
    final DeliveryMethod type,
    final ObservableFactory<A, T> observableFactory) {

    return channel(type, new Func1<Object, Observable<Notification<T>>>() {
        @Override
        public Observable<Notification<T>> call(final Object arg) {
            return ReconnectableMap.INSTANCE.channel(key, type, new Func0<Observable<T>>() {
                @Override
                public Observable<T> call() {
                    return observableFactory.call((A) arg);
                }
            });
        }
    });
}
 
Example #3
Source File: Stopwatches.java    From ocelli with Apache License 2.0 6 votes vote down vote up
/**
 * Stopwatch that calls System.nanoTime()
 * 
 * @return
 */
public static Func0<Stopwatch> systemNano() {
    return new Func0<Stopwatch>() {
        @Override
        public Stopwatch call() {
            return new Stopwatch() {
                private final long startTime = System.nanoTime();
                
                @Override
                public long elapsed(TimeUnit units) {
                    return units.convert(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
                }
            };
        }
    };
}
 
Example #4
Source File: HealthPinger.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
/**
 * Pings the service and completes if successful - and fails if it didn't work
 * for some reason (reason is in the exception).
 */
private static Observable<PingServiceHealth> pingQuery(
    final String hostname, final String bucket, final String password,
    final ClusterFacade core, final long timeout, final TimeUnit timeUnit) {
    final AtomicReference<CouchbaseRequest> request = new AtomicReference<CouchbaseRequest>();
    Observable<com.couchbase.client.core.message.query.PingResponse> response =
        Observable.defer(new Func0<Observable<com.couchbase.client.core.message.query.PingResponse>>() {
        @Override
        public Observable<com.couchbase.client.core.message.query.PingResponse> call() {
            CouchbaseRequest r;
            try {
                r = new com.couchbase.client.core.message.query.PingRequest(hostname, bucket, password);
            } catch (Exception e) {
                return Observable.error(e);
            }
            request.set(r);
            return core.send(r);
        }
    }).timeout(timeout, timeUnit);
    return mapToServiceHealth(null, ServiceType.QUERY, response, request, timeout, timeUnit);
}
 
Example #5
Source File: EurekaInterestManager.java    From ocelli with Apache License 2.0 6 votes vote down vote up
private Observable<Instance<InstanceInfo>> create(final Func0<List<InstanceInfo>> lister) {
    return Observable
            .interval(interval, intervalUnits, scheduler)
            .onBackpressureDrop()
            .flatMap(new Func1<Long, Observable<List<InstanceInfo>>>() {
                @Override
                public Observable<List<InstanceInfo>> call(Long t1) {
                    try {
                        return Observable.just(lister.call());
                    }
                    catch (Exception e) {
                        return Observable.empty();
                    }
                }
            }, 1)
            .serialize()
            .compose(new SnapshotToInstance<InstanceInfo>());
}
 
Example #6
Source File: RxPresenterTest.java    From nucleus with MIT License 6 votes vote down vote up
@Test
public void testCompletedRestartable() throws Exception {
    Func0<Subscription> restartable = mock(Func0.class);
    Subscription subscription = mock(Subscription.class);

    RxPresenter presenter = new RxPresenter();
    presenter.create(null);

    when(restartable.call()).thenReturn(subscription);
    when(subscription.isUnsubscribed()).thenReturn(true);
    presenter.restartable(1, restartable);

    verifyNoMoreInteractions(restartable);

    presenter.start(1);
}
 
Example #7
Source File: ParallelDocumentQueryExecutionContext.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
protected DocumentProducer<T> createDocumentProducer(
        String collectionRid,
        PartitionKeyRange targetRange,
        String initialContinuationToken,
        int initialPageSize,
        FeedOptions feedOptions,
        SqlQuerySpec querySpecForInit,
        Map<String, String> commonRequestHeaders,
        Func3<PartitionKeyRange, String, Integer, RxDocumentServiceRequest> createRequestFunc,
        Func1<RxDocumentServiceRequest, Observable<FeedResponse<T>>> executeFunc,
        Func0<IDocumentClientRetryPolicy> createRetryPolicyFunc) {
    return new DocumentProducer<T>(client,
            collectionRid,
            feedOptions,
            createRequestFunc,
            executeFunc,
            targetRange,
            collectionRid,
            () -> client.getResetSessionTokenRetryPolicy().getRequestPolicy(),
            resourceType,
            correlatedActivityId,
            initialPageSize,
            initialContinuationToken,
            top);
}
 
Example #8
Source File: RxFile.java    From RxFile with Apache License 2.0 6 votes vote down vote up
private static Observable<List<File>> createFileFromUri(final Context context,
    final ArrayList<Uri> uris, final MimeMap mimeTypeMap) {
  return Observable.defer(new Func0<Observable<List<File>>>() {
    @Override
    public Observable<List<File>> call() {

      List<File> filesRetrieved = new ArrayList<>(uris.size());

      for (Uri data : uris) {
        try {
          filesRetrieved.add(fileFromUri(context, data, mimeTypeMap));
        } catch (Exception e) {
          logError(e);
          return Observable.error(e);
        }
      }

      return Observable.just(filesRetrieved);
    }
  });
}
 
Example #9
Source File: ObservableServerSocket.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
public static Observable<Observable<byte[]>> create(
        final Func0<? extends ServerSocket> serverSocketFactory, final int timeoutMs,
        final int bufferSize, Action0 preAcceptAction, int acceptTimeoutMs,
        Func1<? super Socket, Boolean> acceptSocket) {
    Func1<ServerSocket, Observable<Observable<byte[]>>> observableFactory = createObservableFactory(
            timeoutMs, bufferSize, preAcceptAction, acceptSocket);
    return Observable.<Observable<byte[]>, ServerSocket> using( //
            createServerSocketFactory(serverSocketFactory, acceptTimeoutMs), //
            observableFactory, //
            new Action1<ServerSocket>() {

                @Override
                public void call(ServerSocket ss) {
                    try {
                        ss.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

            }, true);
}
 
Example #10
Source File: AirMapClient.java    From AirMapSDK-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Make a POST call without params
 *
 * @param url The full url to POST
 */
public <T extends AirMapBaseModel> Observable<T> post(final String url, final Class<T> classToInstantiate) {
    return Observable.defer(new Func0<Observable<T>>() {
        @Override
        public Observable<T> call() {
            try {
                Request request = new Builder().url(url).post(bodyFromMap(null)).tag(url).build();
                Response response = client.newCall(request).execute();
                T model = parseResponse(response, classToInstantiate);

                return Observable.just(model);
            } catch (IOException | IllegalAccessException | InstantiationException | JSONException | AirMapException e) {
                return Observable.error(e);
            }
        }
    });
}
 
Example #11
Source File: ProfileActivity.java    From openwebnet-android with MIT License 6 votes vote down vote up
private <T> void requestAction(Func0<Observable<T>> observableAction, Action1<T> onSuccess) {
    hideActions();

    if (utilityService.hasInternetAccess()) {
        observableAction.call()
            // better UX
            .delay(1 , TimeUnit.SECONDS)
            // max http timeout
            .timeout(5, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(onSuccess, error -> {
                swipeRefreshLayoutProfile.setRefreshing(false);
                log.error("requestAction: request failed", error);
                showSnackbar(R.string.error_request);
            });
    } else {
        // show empty list
        updateProfiles(Lists.newArrayList());
        // hide
        speedDialProfile.hide();
        log.warn("requestAction: connection unavailable");
        showSnackbar(R.string.error_connection);
    }
}
 
Example #12
Source File: PayDeveloperManager.java    From jianshi with Apache License 2.0 6 votes vote down vote up
public Observable<PayDeveloperDialogData> getPayDeveloperDialogData() {
  return Observable.defer(new Func0<Observable<PayDeveloperDialogData>>() {
    @Override
    public Observable<PayDeveloperDialogData> call() {
      return userService.payDeveloper()
          .flatMap(new Func1<JsonDataResponse<PayDeveloperDialogData>, Observable<PayDeveloperDialogData>>() {
            @Override
            public Observable<PayDeveloperDialogData> call(JsonDataResponse<PayDeveloperDialogData> response) {
              if (response.getRc() == Constants.ServerResultCode.RESULT_OK) {
                return Observable.just(response.getData());
              } else {
                return Observable.just(null);
              }
            }
          })
          .subscribeOn(Schedulers.io());
    }
  });
}
 
Example #13
Source File: TransformerStateMachineTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testStateTransitionThrowsError() {
    final RuntimeException ex = new RuntimeException("boo");
    Func0<Integer> initialState = Functions.constant0(1);
    Func3<Integer, Integer, Observer<Integer>, Integer> transition = new Func3<Integer, Integer, Observer<Integer>, Integer>() {

        @Override
        public Integer call(Integer collection, Integer t, Observer<Integer> observer) {
            throw ex;
        }

    };
    Func2<Integer, Observer<Integer>, Boolean> completion = Functions.alwaysTrue2();
    Transformer<Integer, Integer> transformer = Transformers.stateMachine(initialState,
            transition, completion);
    TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
    Observable.just(1, 1, 1).compose(transformer).subscribe(ts);
    ts.awaitTerminalEvent();
    ts.assertError(ex);
}
 
Example #14
Source File: TransformerStateMachineTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testForCompletionWithinStateMachine() {
    Func0<Integer> initialState = Functions.constant0(1);
    Func3<Integer, Integer, Subscriber<Integer>, Integer> transition = new Func3<Integer, Integer, Subscriber<Integer>, Integer>() {

        @Override
        public Integer call(Integer collection, Integer t, Subscriber<Integer> subscriber) {
            subscriber.onNext(123);
            // complete from within transition
            subscriber.onCompleted();
            return 1;
        }

    };
    Func2<? super Integer, ? super Subscriber<Integer>, Boolean> completion = Functions
            .alwaysTrue2();
    Transformer<Integer, Integer> transformer = Transformers.stateMachine(initialState,
            transition, completion);
    TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
    final AtomicInteger count = new AtomicInteger(0);
    Observable.just(1, 2, 3).doOnNext(Actions.increment1(count)).compose(transformer)
            .subscribe(ts);
    ts.assertValues(123);
    ts.assertCompleted();
    assertEquals(1, count.get());
}
 
Example #15
Source File: ObsTest.java    From rxjava-extras with Apache License 2.0 6 votes vote down vote up
@Test
public void testCachedScheduledReset() {
    TestScheduler scheduler = new TestScheduler();
    Worker worker = scheduler.createWorker();
    try {
        final AtomicInteger count = new AtomicInteger(0);
        Observable<Integer> source = Observable.defer(new Func0<Observable<Integer>>() {
            @Override
            public Observable<Integer> call() {
                return Observable.just(count.incrementAndGet());
            }
        })
                // cache
                .compose(Transformers.<Integer> cache(5, TimeUnit.MINUTES, worker));
        assertEquals(1, (int) source.toBlocking().single());
        scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
        assertEquals(1, (int) source.toBlocking().single());
        scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
        assertEquals(1, (int) source.toBlocking().single());
        scheduler.advanceTimeBy(3, TimeUnit.MINUTES);
        assertEquals(2, (int) source.toBlocking().single());
        assertEquals(2, (int) source.toBlocking().single());
    } finally {
        worker.unsubscribe();
    }
}
 
Example #16
Source File: TaskGroup.java    From autorest-clientruntime-for-java with MIT License 6 votes vote down vote up
/**
 * Invokes tasks in the group.
 *
 * @param context group level shared context that need be passed to invokeAsync(cxt)
 *                method of each task item in the group when it is selected for invocation.
 *
 * @return an observable that emits the result of tasks in the order they finishes.
 */
public Observable<Indexable> invokeAsync(final InvocationContext context) {
    return Observable.defer(new Func0<Observable<Indexable>>() {
        @Override
        public Observable<Indexable> call() {
            if (proxyTaskGroupWrapper.isActive()) {
                return proxyTaskGroupWrapper.taskGroup()
                        .invokeInternAsync(context, true, null);
            } else {
                Set<String> processedKeys = runBeforeGroupInvoke(null);
                if (proxyTaskGroupWrapper.isActive()) {
                    // If proxy got activated after 'runBeforeGroupInvoke()' stage due to the addition of direct
                    // 'postRunDependent's then delegate group invocation to proxy group.
                    //
                    return proxyTaskGroupWrapper.taskGroup()
                            .invokeInternAsync(context, true, processedKeys);
                } else {
                    return invokeInternAsync(context, false, null);
                }
            }
        }
    });
}
 
Example #17
Source File: TaskGroup.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Invokes tasks in the group.
 *
 * @param context group level shared context that need be passed to invokeAsync(cxt)
 *                method of each task item in the group when it is selected for invocation.
 *
 * @return an observable that emits the result of tasks in the order they finishes.
 */
public Observable<Indexable> invokeAsync(final InvocationContext context) {
    return Observable.defer(new Func0<Observable<Indexable>>() {
        @Override
        public Observable<Indexable> call() {
            if (proxyTaskGroupWrapper.isActive()) {
                return proxyTaskGroupWrapper.taskGroup()
                        .invokeInternAsync(context, true, null);
            } else {
                Set<String> processedKeys = runBeforeGroupInvoke(null);
                if (proxyTaskGroupWrapper.isActive()) {
                    // If proxy got activated after 'runBeforeGroupInvoke()' stage due to the addition of direct
                    // 'postRunDependent's then delegate group invocation to proxy group.
                    //
                    return proxyTaskGroupWrapper.taskGroup()
                            .invokeInternAsync(context, true, processedKeys);
                } else {
                    return invokeInternAsync(context, false, null);
                }
            }
        }
    });
}
 
Example #18
Source File: TaskGroupEntry.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Invokes the task this entry holds.
 * if the task cannot be invoked due to faulted dependencies then an observable that emit
 * {@link ErroredDependencyTaskException} will be returned.
 *
 * @param ignoreCachedResult if the task is already invoked and has result cached then a value false for this
 *                           parameter indicates the cached result can be returned without invoking task again,
 *                           if true then cached result will be ignored and task will be invoked
 * @param context the context object shared across all the entries in the group that this entry belongs to,
 *                this will be passed to {@link TaskItem#invokeAsync(TaskGroup.InvocationContext)}
 *                method of the task item
 *
 * @return a cold Observable upon subscription invokes the task this entry hold, which produces a result of
 * type {@link Indexable}.
 */
public Observable<Indexable> invokeTaskAsync(boolean ignoreCachedResult, final TaskGroup.InvocationContext context) {
    if (hasFaultedDescentDependencyTasks) {
        return Observable.error(new ErroredDependencyTaskException());
    }
    final TaskT taskItem = this.taskItem();
    if (!ignoreCachedResult && hasCachedResult()) {
        return Observable.just(taskItem.result());
    }
    if (taskItem.isHot()) {
        // Convert hot task to cold to delay it's execution until subscription.
        return Observable.defer(new Func0<Observable<Indexable>>() {
            @Override
            public Observable<Indexable> call() {
                return taskItem.invokeAsync(context);
            }
        });
    } else {
        return taskItem.invokeAsync(context);
    }
}
 
Example #19
Source File: BillingProcessor.java    From RxIAPv3 with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<List<String>> listOwnedProductsObservable() {
    return Observable.fromCallable(new Func0<List<String>>() {
        @Override
        public List<String> call() {
            return cachedProducts.getProductIds();
        }
    });
}
 
Example #20
Source File: RxBaseDaoImpl.java    From AndroidStarter with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<Long> rxQueryRawValue(final String query, final String... arguments) {
    final Func0<Observable<Long>> loFunc = () -> {
        try {
            return Observable.just(queryRawValue(query, arguments));
        } catch (SQLException e) {
            return Observable.error(e);
        }
    };
    return Observable.defer(loFunc);
}
 
Example #21
Source File: EurekaInterestManager.java    From ocelli with Apache License 2.0 5 votes vote down vote up
private Func0<List<InstanceInfo>> _forVip(final String vip, final boolean secure) {
    return new Func0<List<InstanceInfo>>() {
        @Override
        public List<InstanceInfo> call() {
            return client.getInstancesByVipAddress(vip, secure);
        }
    };
}
 
Example #22
Source File: RxSnappyClient.java    From rxsnappy with Apache License 2.0 5 votes vote down vote up
public Observable<List<String>> getStringList(final String key, final Long cacheTime) {
    return Observable.defer(new Func0<Observable<List<String>>>() {
        @Override
        public Observable<List<String>> call() {
            try {
                return Observable.just(getStringListValue(key, cacheTime));
            } catch (Exception e) {
                return Observable.error(e);
            }
        }
    });
}
 
Example #23
Source File: ResourceManager.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
protected ResourceManager(Func0<T> resourceFactory, Action1<? super T> disposeAction,
        boolean disposeEagerly) {
    Preconditions.checkNotNull(resourceFactory);
    Preconditions.checkNotNull(disposeAction);
    this.resourceFactory = resourceFactory;
    this.disposeAction = disposeAction;
    this.disposeEagerly = disposeEagerly;
}
 
Example #24
Source File: RxBaseDaoImpl.java    From AndroidStarter with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<Integer> rxDelete(final Collection<DataType> datas) {
    final Func0<Observable<Integer>> loFunc = () -> {
        try {
            return Observable.just(delete(datas));
        } catch (SQLException e) {
            return Observable.error(e);
        }
    };
    return Observable.defer(loFunc);
}
 
Example #25
Source File: BlurredBackgroundAdapter.java    From fogger with Apache License 2.0 5 votes vote down vote up
private void blur(Context context, Func0<Bitmap> screenShotProvider) {
    Async.start(screenShotProvider)
            .subscribeOn(Schedulers.computation())
            .map(screenShot -> BlurringMachineFactory.create(context).blur(screenShot))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(blurredBitmap -> onBlurringFinish(blurredBitmap));
}
 
Example #26
Source File: RxSnappyClient.java    From rxsnappy with Apache License 2.0 5 votes vote down vote up
public <T> Observable<T> getObject(final String key, final Long cacheTime, final Class<T> selectedClass) {
    return Observable.defer(new Func0<Observable<T>>() {
        @Override
        public Observable<T> call() {
            try {
                return Observable.just(getObjectValue(key, cacheTime, selectedClass));
            } catch (Exception e) {
                return Observable.error(e);
            }
        }
    });
}
 
Example #27
Source File: Functions.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <T> Func0<T> toFunc0(final Callable<T> f) {
    return new Func0<T>() {

        @Override
        public T call() {
            try {
                return f.call();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
}
 
Example #28
Source File: Transformers.java    From rxjava-extras with Apache License 2.0 5 votes vote down vote up
public static <State, In, Out> Transformer<In, Out> stateMachine(
        Func0<State> initialStateFactory,
        Func3<? super State, ? super In, ? super Subscriber<Out>, ? extends State> transition,
        Func2<? super State, ? super Subscriber<Out>, Boolean> completion,
        BackpressureStrategy backpressureStrategy, int initialRequest) {
    return TransformerStateMachine.<State, In, Out> create(initialStateFactory, transition,
            completion, backpressureStrategy, initialRequest);
}
 
Example #29
Source File: ConnectionGroup.java    From mantis with Apache License 2.0 5 votes vote down vote up
public ConnectionGroup(String groupId) {
    this.groupId = groupId;
    this.connections = new HashMap<>();

    final String grpId = Optional.ofNullable(groupId).orElse("none");
    final BasicTag groupIdTag = new BasicTag(MantisMetricStringConstants.GROUP_ID_TAG, grpId);
    this.metricsGroup = new MetricGroupId("ConnectionGroup", groupIdTag);

    Gauge activeConnections
            = new GaugeCallback(metricsGroup, "activeConnections", new Func0<Double>() {
        @Override
        public Double call() {
            synchronized (this) {
                return (double) connections.size();
            }
        }
    });
    this.metrics = new Metrics.Builder()
            .id(metricsGroup)
            .addCounter("numSlotSwaps")
            .addCounter("numSuccessfulWrites")
            .addCounter("numFailedWrites")
            .addGauge(activeConnections)
            .build();

    this.successfulWrites = metrics.getCounter("numSuccessfulWrites");
    this.failedWrites = metrics.getCounter("numFailedWrites");
    this.numSlotSwaps = metrics.getCounter("numSlotSwaps");
}
 
Example #30
Source File: RxBaseDaoImpl.java    From AndroidStarter with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<Integer> rxDeleteById(final IdType id) {
    final Func0<Observable<Integer>> loFunc = () -> {
        try {
            return Observable.just(deleteById(id));
        } catch (SQLException e) {
            return Observable.error(e);
        }
    };
    return Observable.defer(loFunc);
}