Java Code Examples for rx.functions.Action0#call()

The following examples show how to use rx.functions.Action0#call() . 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: DnsZoneRecordSetETagTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Runs the action and assert that action throws CloudException with CloudError.Code
 * property set to 'PreconditionFailed'.
 *
 * @param action action to run
 */
private void ensureETagExceptionIsThrown(final Action0 action) {
    boolean isCloudExceptionThrown = false;
    boolean isCloudErrorSet = false;
    boolean isPreconditionFailedCodeSet = false;
    try {
        action.call();
    } catch (CloudException exception) {
        isCloudExceptionThrown = true;
        CloudError cloudError = exception.body();
        if (cloudError != null) {
            isCloudErrorSet = true;
            isPreconditionFailedCodeSet = cloudError.code().contains("PreconditionFailed");
        }
    }
    Assert.assertTrue("Expected CloudException is not thrown", isCloudExceptionThrown);
    Assert.assertTrue("Expected CloudError property is not set in CloudException", isCloudErrorSet);
    Assert.assertTrue("Expected PreconditionFailed code is not set indicating ETag concurrency check failure", isPreconditionFailedCodeSet);
}
 
Example 2
Source File: GrpcUtil.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public static <REQ, RESP> ClientResponseObserver<REQ, RESP> createClientResponseObserver(final Action1<ClientCallStreamObserver<REQ>> beforeStart,
                                                                                         final Action1<? super RESP> onNext,
                                                                                         final Action1<Throwable> onError,
                                                                                         final Action0 onCompleted) {
    return new ClientResponseObserver<REQ, RESP>() {
        @Override
        public void beforeStart(ClientCallStreamObserver<REQ> requestStream) {
            beforeStart.call(requestStream);
        }

        @Override
        public void onNext(RESP value) {
            onNext.call(value);
        }

        @Override
        public void onError(Throwable t) {
            onError.call(t);
        }

        @Override
        public void onCompleted() {
            onCompleted.call();
        }
    };
}
 
Example 3
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 4
Source File: WriteStreamSubscriberImpl.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
private void writeStreamEnd(AsyncResult<Void> result) {
  Action0 a;
  if (result.succeeded()) {
    synchronized (this) {
      a = writeStreamEndHandler;
    }
    if (a != null) {
      a.call();
    }
  } else {
    Action1<Throwable> c;
    synchronized (this) {
      c = this.writeStreamEndErrorHandler;
    }
    if (c != null) {
      c.call(result.cause());
    }
  }
}
 
Example 5
Source File: SchedulerImpl.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
private void doOnTick(Action0 action) {
    Action0 wrapper = () -> {
        Date timeSlice = getTimeSlice(new DateTime(tickScheduler.now()), minutes(1).toStandardDuration()).toDate();
        action.call();
    };
    AtomicReference<DateTime> previousTimeSliceRef = new AtomicReference<>();
    // TODO Emit ticks at the start of every minute
    Observable.interval(0, 1, TimeUnit.MINUTES, tickScheduler)
            .filter(tick -> {
                DateTime time = currentMinute();
                if (previousTimeSliceRef.get() == null) {
                    previousTimeSliceRef.set(time);
                    return true;
                }
                if (previousTimeSliceRef.get().equals(time)) {
                    return false;
                }
                previousTimeSliceRef.set(time);
                return true;
            })
            .takeUntil(d -> !running)
            .subscribe(tick -> wrapper.call(), t -> logger.warn(t));
}
 
Example 6
Source File: RxUtil.java    From ocelli with Apache License 2.0 6 votes vote down vote up
/**
 * Utility to call an action when any event occurs regardless that event
 * @param action
 * @return
 */
public static <T> Observer<T> onAny(final Action0 action) {
    return new Observer<T>() {

        @Override
        public void onCompleted() {
            action.call();
        }

        @Override
        public void onError(Throwable e) {
            action.call();
        }

        @Override
        public void onNext(T t) {
            action.call();
        }
    } ;
}
 
Example 7
Source File: PermissionServiceActivity.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M) @Override
public void hasDownloadAccess(@Nullable Action0 accessGranted, @Nullable Action0 accessDenied) {
  int externalStoragePermission =
      ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

  if (externalStoragePermission == PackageManager.PERMISSION_GRANTED) {
    if (!(AptoideUtils.SystemU.getConnectionType(connectivityManager)
        .equals("mobile") && !ManagerPreferences.getDownloadsWifiOnly(sharedPreferences))) {
      if (accessGranted != null) {
        accessGranted.call();
      }
      return;
    }
  }
  if (accessDenied != null) {
    accessDenied.call();
  }
}
 
Example 8
Source File: SleuthRxJavaSchedulersHookTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_wrap_delegates_action_in_wrapped_action_when_delegate_is_present_on_schedule() {
	RxJavaPlugins.getInstance().registerSchedulersHook(new MyRxJavaSchedulersHook());
	SleuthRxJavaSchedulersHook schedulersHook = new SleuthRxJavaSchedulersHook(
			this.tracer, this.threadsToIgnore);
	Action0 action = schedulersHook.onSchedule(() -> {
		caller = new StringBuilder("hello");
	});

	action.call();

	then(action).isInstanceOf(SleuthRxJavaSchedulersHook.TraceAction.class);
	then(caller.toString()).isEqualTo("called_from_schedulers_hook");
	then(this.spans).isNotEmpty();
	then(this.tracer.currentSpan()).isNull();
}
 
Example 9
Source File: ResponseBuilder.java    From ReactiveLab with Apache License 2.0 5 votes vote down vote up
public static void writeTestResponse(Writer writer, BackendResponse responseA, BackendResponse responseB,
        BackendResponse responseC, BackendResponse responseD, BackendResponse responseE, Action0 onComplete) {
    try {
        JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer);
        generateResponse(responseA, responseB, responseC, responseD, responseE, jsonGenerator);
        if (onComplete != null) {
            onComplete.call();
        }
        jsonGenerator.close();
    } catch (Exception e) {
        throw new RuntimeException("failed to generated response", e);
    }

}
 
Example 10
Source File: PushServer.java    From mantis with Apache License 2.0 5 votes vote down vote up
protected void connectionCleanup(Subscription heartbeatSubscription, Action0 connectionClosedCallback, Subscription metaMsgSubscription) {
    if (heartbeatSubscription != null) {
        logger.info("Unsubscribing from heartbeats");
        heartbeatSubscription.unsubscribe();
    }
    if (metaMsgSubscription != null) {
        logger.info("Unsubscribing from metaMsg subject");
        metaMsgSubscription.unsubscribe();
    }

    if (connectionClosedCallback != null) {
        connectionClosedCallback.call();
    }
}
 
Example 11
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 12
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 13
Source File: BaseUseCaseTest.java    From buddysearch with Apache License 2.0 5 votes vote down vote up
protected void testBuildUseCaseObservable(Object requestData, Action0 action) {
    useCase.buildObservable(requestData);
    action.call();
    verifyNoMoreInteractions(mockRepository);
    verifyZeroInteractions(mockThreadScheduler);
    verifyZeroInteractions(mockPostExecutionScheduler);
}
 
Example 14
Source File: TestSubscriber2.java    From rxjava-extras with Apache License 2.0 4 votes vote down vote up
public final TestSubscriber2<T> perform(Action0 action) {
    action.call();
    return this;
}
 
Example 15
Source File: PermissionServiceActivity.java    From aptoide-client-v8 with GNU General Public License v3.0 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M) @Override
public void requestAccessToExternalFileSystem(boolean forceShowRationale,
    @StringRes int rationaleMessage, @Nullable Action0 toRunWhenAccessIsGranted,
    @Nullable Action0 toRunWhenAccessIsDenied) {
  int hasPermission =
      ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
  if (hasPermission != PackageManager.PERMISSION_GRANTED) {
    this.toRunWhenAccessToFileSystemIsGranted = toRunWhenAccessIsGranted;
    this.toRunWhenAccessToFileSystemIsDenied = toRunWhenAccessIsDenied;

    if (forceShowRationale || ActivityCompat.shouldShowRequestPermissionRationale(this,
        Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
      Logger.getInstance()
          .v(TAG, "showing rationale and requesting permission to access external storage");

      // TODO: 19/07/16 improve this rationale messages
      showMessageOKCancel(rationaleMessage, new SimpleSubscriber<GenericDialogs.EResponse>() {

        @Override public void onNext(GenericDialogs.EResponse eResponse) {
          super.onNext(eResponse);
          if (eResponse != GenericDialogs.EResponse.YES) {
            if (toRunWhenAccessToFileSystemIsDenied != null) {
              toRunWhenAccessToFileSystemIsDenied.call();
            }
            return;
          }

          ActivityCompat.requestPermissions(PermissionServiceActivity.this, new String[] {
              Manifest.permission.WRITE_EXTERNAL_STORAGE,
              Manifest.permission.READ_EXTERNAL_STORAGE
          }, ACCESS_TO_EXTERNAL_FS_REQUEST_ID);
        }
      });
      return;
    }

    ActivityCompat.requestPermissions(this, new String[] {
        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    }, ACCESS_TO_EXTERNAL_FS_REQUEST_ID);
    Logger.getInstance()
        .v(TAG, "requesting permission to access external storage");
    return;
  }
  Logger.getInstance()
      .v(TAG, "already has permission to access external storage");
  if (toRunWhenAccessIsGranted != null) {
    toRunWhenAccessIsGranted.call();
  }
}
 
Example 16
Source File: PermissionServiceActivity.java    From aptoide-client-v8 with GNU General Public License v3.0 4 votes vote down vote up
@Override public void requestAccessToCamera(@Nullable Action0 toRunWhenAccessIsGranted,
    @Nullable Action0 toRunWhenAccessIsDenied) {
  int hasPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
  if (hasPermission != PackageManager.PERMISSION_GRANTED) {
    this.toRunWhenAccessToFileSystemIsGranted = toRunWhenAccessIsGranted;
    this.toRunWhenAccessToFileSystemIsDenied = toRunWhenAccessIsDenied;

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
      Logger.getInstance()
          .v(TAG, "showing rationale and requesting permission to access camera");

      showMessageOKCancel(R.string.camera_access_permission_request_message,
          new SimpleSubscriber<GenericDialogs.EResponse>() {

            @Override public void onNext(GenericDialogs.EResponse eResponse) {
              super.onNext(eResponse);
              if (eResponse != GenericDialogs.EResponse.YES) {
                if (toRunWhenAccessToFileSystemIsDenied != null) {
                  toRunWhenAccessToFileSystemIsDenied.call();
                }
                return;
              }

              ActivityCompat.requestPermissions(PermissionServiceActivity.this, new String[] {
                  Manifest.permission.CAMERA
              }, PERMISSIONS_REQUEST_ACCESS_CAMERA);
            }
          });
      return;
    }

    ActivityCompat.requestPermissions(PermissionServiceActivity.this, new String[] {
        Manifest.permission.CAMERA
    }, PERMISSIONS_REQUEST_ACCESS_CAMERA);
    Logger.getInstance()
        .v(TAG, "requesting permission to access camera");
    return;
  }
  Logger.getInstance()
      .v(TAG, "already has permission to access camera");
  if (toRunWhenAccessIsGranted != null) {
    toRunWhenAccessIsGranted.call();
  }
}
 
Example 17
Source File: PermissionServiceActivity.java    From aptoide-client-v8 with GNU General Public License v3.0 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M) @Override
public void requestAccessToAccounts(boolean forceShowRationale,
    @Nullable Action0 toRunWhenAccessIsGranted, @Nullable Action0 toRunWhenAccessIsDenied) {
  int hasPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS);
  if (hasPermission != PackageManager.PERMISSION_GRANTED) {
    this.toRunWhenAccessToAccountsIsGranted = toRunWhenAccessIsGranted;
    this.toRunWhenAccessToAccountsIsDenied = toRunWhenAccessIsDenied;

    if (forceShowRationale || ActivityCompat.shouldShowRequestPermissionRationale(this,
        Manifest.permission.GET_ACCOUNTS)) {
      Logger.getInstance()
          .v(TAG, "showing rationale and requesting permission to access accounts");

      showMessageOKCancel(R.string.access_to_get_accounts_rationale,
          new SimpleSubscriber<GenericDialogs.EResponse>() {

            @Override public void onNext(GenericDialogs.EResponse eResponse) {
              super.onNext(eResponse);
              if (eResponse != GenericDialogs.EResponse.YES) {
                if (toRunWhenAccessToAccountsIsDenied != null) {
                  toRunWhenAccessToAccountsIsDenied.call();
                }
                return;
              }

              ActivityCompat.requestPermissions(PermissionServiceActivity.this, new String[] {
                  Manifest.permission.GET_ACCOUNTS
              }, ACCESS_TO_ACCOUNTS_REQUEST_ID);
            }
          });
      return;
    }

    ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.GET_ACCOUNTS },
        ACCESS_TO_ACCOUNTS_REQUEST_ID);
    Logger.getInstance()
        .v(TAG, "requesting permission to access accounts");
    return;
  }
  Logger.getInstance()
      .v(TAG, "already has permission to access accounts");
  if (toRunWhenAccessIsGranted != null) {
    toRunWhenAccessIsGranted.call();
  }
}