com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter Java Examples

The following examples show how to use com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter. 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: RNFusedLocationModule.java    From react-native-geolocation-service with MIT License 6 votes vote down vote up
/**
 * Helper method to invoke success callback
 */
private void invokeSuccess(WritableMap data, boolean isSingleUpdate) {
  if (!isSingleUpdate) {
    getContext().getJSModule(RCTDeviceEventEmitter.class)
      .emit("geolocationDidChange", data);

    return;
  }

  try {
    if (mSuccessCallback != null) {
      mSuccessCallback.invoke(data);
    }

    clearCallbacks();
  } catch (RuntimeException e) {
    // Illegal callback invocation
    Log.w(TAG, e.getMessage());
  }
}
 
Example #2
Source File: RNFusedLocationModule.java    From react-native-geolocation-service with MIT License 6 votes vote down vote up
/**
 * Helper method to invoke error callback
 */
private void invokeError(int code, String message, boolean isSingleUpdate) {
  if (!isSingleUpdate) {
    getContext().getJSModule(RCTDeviceEventEmitter.class)
      .emit("geolocationError", LocationUtils.buildError(code, message));

    return;
  }

  try {
    if (mErrorCallback != null) {
      mErrorCallback.invoke(LocationUtils.buildError(code, message));
    }

    clearCallbacks();
  } catch (RuntimeException e) {
    // Illegal callback invocation
    Log.w(TAG, e.getMessage());
  }
}
 
Example #3
Source File: NetworkingModule.java    From react-native-GPay with MIT License 6 votes vote down vote up
private RequestBody wrapRequestBodyWithProgressEmitter(
    final RequestBody requestBody,
    final RCTDeviceEventEmitter eventEmitter,
    final int requestId) {
  if(requestBody == null) {
    return null;
  }
  return RequestBodyUtil.createProgressRequest(
    requestBody,
    new ProgressListener() {
      long last = System.nanoTime();

      @Override
      public void onProgress(long bytesWritten, long contentLength, boolean done) {
        long now = System.nanoTime();
        if (done || shouldDispatch(now, last)) {
          ResponseUtil.onDataSend(eventEmitter, requestId, bytesWritten, contentLength);
          last = now;
        }
      }
    });
}
 
Example #4
Source File: ReactNativeUtils.java    From native-navigation with MIT License 6 votes vote down vote up
/** Emits a JS event with the provided name and data if the rect context is initialized */
static void maybeEmitEvent(ReactContext context, String name, Object data) {
  if (context == null) {
    throw new IllegalArgumentException(
        String.format("reactContext is null (calling event: %s)", name));
  }
  if (context.hasActiveCatalystInstance()) {
    try {
      context.getJSModule(RCTDeviceEventEmitter.class).emit(name, data);
    } catch (RuntimeException e) {
      // the JS bundle hasn't finished executing, so this call is going to be lost.
      // In the future, we could maybe set something up to queue the call, and then pass them through once
      // the bundle has finished getting parsed, but for now I am going to just swallow the error.
    }
  }
}
 
Example #5
Source File: RNLocationModule.java    From react-native-gps with MIT License 5 votes vote down vote up
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
  if (reactContext.hasActiveCatalystInstance()) {
    reactContext
      .getJSModule(RCTDeviceEventEmitter.class)
      .emit(eventName, params);
  } else {
    Log.i(TAG, "Waiting for CatalystInstance...");
  }
}
 
Example #6
Source File: RNLocationModule.java    From react-native-gps with MIT License 5 votes vote down vote up
private void emitError(int code, String message) {
  WritableMap error = Arguments.createMap();
  error.putInt("code", code);

  if (message != null) {
    error.putString("message", message);
  }

  getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class)
    .emit("geolocationError", error);
}
 
Example #7
Source File: RNDevMenuModule.java    From react-native-dev-menu with MIT License 5 votes vote down vote up
@ReactMethod
public void addItem(final String name, Promise promise) {
  if (mNames == null) {
    mNames = new ArrayList<>();
  }
  if (mNames.contains(name)) {
    promise.resolve(null);
  }

  try {
    ReactApplication application = (ReactApplication)getReactApplicationContext()
      .getCurrentActivity()
      .getApplication();

    DevSupportManager manager = application
      .getReactNativeHost()
      .getReactInstanceManager()
      .getDevSupportManager();

    manager.addCustomDevOption(name, new DevOptionHandler() {
      @Override
      public void onOptionSelected() {
        getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class)
                .emit("customDevOptionTap", name);
      }
    });

    mNames.add(name);
    promise.resolve(null);
  } catch (Exception e) {
    promise.reject(e);
  }
}
 
Example #8
Source File: NetworkingModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
private static void verifyErrorEmit(RCTDeviceEventEmitter emitter, int requestId) {
  ArgumentCaptor<WritableArray> captor = ArgumentCaptor.forClass(WritableArray.class);
  verify(emitter).emit(eq("didCompleteNetworkResponse"), captor.capture());

  WritableArray array = captor.getValue();
  assertThat(array.getInt(0)).isEqualTo(requestId);
  assertThat(array.getString(1)).isNotNull();
}
 
Example #9
Source File: NetworkingModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void testFailInvalidUrl() throws Exception {
  RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class);
  ReactApplicationContext context = mock(ReactApplicationContext.class);
  when(context.getJSModule(any(Class.class))).thenReturn(emitter);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class);
  when(clientBuilder.build()).thenReturn(httpClient);
  when(httpClient.newBuilder()).thenReturn(clientBuilder);
  NetworkingModule networkingModule = new NetworkingModule(context, "", httpClient);

  mockEvents();

  networkingModule.sendRequest(
    "GET",
    "aaa",
    /* requestId */ 0,
    /* headers */ JavaOnlyArray.of(),
    /* body */ null,
    /* responseType */ "text",
    /* useIncrementalUpdates*/ true,
    /* timeout */ 0,
    /* withCredentials */ false);

  verifyErrorEmit(emitter, 0);
}
 
Example #10
Source File: NetworkingModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void testFailPostWithoutContentType() throws Exception {
  RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class);
  ReactApplicationContext context = mock(ReactApplicationContext.class);
  when(context.getJSModule(any(Class.class))).thenReturn(emitter);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class);
  when(clientBuilder.build()).thenReturn(httpClient);
  when(httpClient.newBuilder()).thenReturn(clientBuilder);
  NetworkingModule networkingModule = new NetworkingModule(context, "", httpClient);

  JavaOnlyMap body = new JavaOnlyMap();
  body.putString("string", "This is request body");

  mockEvents();

  networkingModule.sendRequest(
    "POST",
    "http://somedomain/bar",
    0,
    JavaOnlyArray.of(),
    body,
    /* responseType */ "text",
    /* useIncrementalUpdates*/ true,
    /* timeout */ 0,
    /* withCredentials */ false);

  verifyErrorEmit(emitter, 0);
}
 
Example #11
Source File: NetworkingModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Test
public void testFailGetWithInvalidHeadersStruct() throws Exception {
  RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class);
  ReactApplicationContext context = mock(ReactApplicationContext.class);
  when(context.getJSModule(any(Class.class))).thenReturn(emitter);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class);
  when(clientBuilder.build()).thenReturn(httpClient);
  when(httpClient.newBuilder()).thenReturn(clientBuilder);
  NetworkingModule networkingModule = new NetworkingModule(context, "", httpClient);

  List<JavaOnlyArray> invalidHeaders = Arrays.asList(JavaOnlyArray.of("foo"));

  mockEvents();

  networkingModule.sendRequest(
    "GET",
    "http://somedoman/foo",
    /* requestId */ 0,
    /* headers */ JavaOnlyArray.from(invalidHeaders),
    /* body */ null,
    /* responseType */ "text",
    /* useIncrementalUpdates*/ true,
    /* timeout */ 0,
    /* withCredentials */ false);

  verifyErrorEmit(emitter, 0);
}
 
Example #12
Source File: ResponseUtil.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static void onResponseReceived(
  RCTDeviceEventEmitter eventEmitter,
  int requestId,
  int statusCode,
  WritableMap headers,
  String url) {
  WritableArray args = Arguments.createArray();
  args.pushInt(requestId);
  args.pushInt(statusCode);
  args.pushMap(headers);
  args.pushString(url);

  eventEmitter.emit("didReceiveNetworkResponse", args);
}
 
Example #13
Source File: ResponseUtil.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static void onRequestSuccess(RCTDeviceEventEmitter eventEmitter, int requestId) {
  WritableArray args = Arguments.createArray();
  args.pushInt(requestId);
  args.pushNull();

  eventEmitter.emit("didCompleteNetworkResponse", args);
}
 
Example #14
Source File: ResponseUtil.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static void onRequestError(
  RCTDeviceEventEmitter eventEmitter,
  int requestId,
  String error,
  IOException e) {
  WritableArray args = Arguments.createArray();
  args.pushInt(requestId);
  args.pushString(error);

  if ((e != null) && (e.getClass() == SocketTimeoutException.class)) {
    args.pushBoolean(true); // last argument is a time out boolean
  }

  eventEmitter.emit("didCompleteNetworkResponse", args);
}
 
Example #15
Source File: ResponseUtil.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static void onDataReceived(
  RCTDeviceEventEmitter eventEmitter,
  int requestId,
  WritableMap data) {
  WritableArray args = Arguments.createArray();
  args.pushInt(requestId);
  args.pushMap(data);

  eventEmitter.emit("didReceiveNetworkData", args);
}
 
Example #16
Source File: ResponseUtil.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static void onDataReceived(
  RCTDeviceEventEmitter eventEmitter,
  int requestId,
  String data) {
  WritableArray args = Arguments.createArray();
  args.pushInt(requestId);
  args.pushString(data);

  eventEmitter.emit("didReceiveNetworkData", args);
}
 
Example #17
Source File: ResponseUtil.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static void onDataReceivedProgress(
  RCTDeviceEventEmitter eventEmitter,
  int requestId,
  long progress,
  long total) {
  WritableArray args = Arguments.createArray();
  args.pushInt(requestId);
  args.pushInt((int) progress);
  args.pushInt((int) total);

  eventEmitter.emit("didReceiveNetworkDataProgress", args);
}
 
Example #18
Source File: ResponseUtil.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static void onIncrementalDataReceived(
  RCTDeviceEventEmitter eventEmitter,
  int requestId,
  String data,
  long progress,
  long total) {
  WritableArray args = Arguments.createArray();
  args.pushInt(requestId);
  args.pushString(data);
  args.pushInt((int) progress);
  args.pushInt((int) total);

  eventEmitter.emit("didReceiveNetworkIncrementalData", args);
}
 
Example #19
Source File: ResponseUtil.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static void onDataSend(
  RCTDeviceEventEmitter eventEmitter,
  int requestId,
  long progress,
  long total) {
  WritableArray args = Arguments.createArray();
  args.pushInt(requestId);
  args.pushInt((int) progress);
  args.pushInt((int) total);
  eventEmitter.emit("didSendNetworkData", args);
}
 
Example #20
Source File: NetworkingModule.java    From react-native-GPay with MIT License 5 votes vote down vote up
private void readWithProgress(
    RCTDeviceEventEmitter eventEmitter,
    int requestId,
    ResponseBody responseBody) throws IOException {
  long totalBytesRead = -1;
  long contentLength = -1;
  try {
    ProgressResponseBody progressResponseBody = (ProgressResponseBody) responseBody;
    totalBytesRead = progressResponseBody.totalBytesRead();
    contentLength = progressResponseBody.contentLength();
  } catch (ClassCastException e) {
    // Ignore
  }

  Charset charset = responseBody.contentType() == null ? StandardCharsets.UTF_8 :
    responseBody.contentType().charset(StandardCharsets.UTF_8);

  ProgressiveStringDecoder streamDecoder = new ProgressiveStringDecoder(charset);
  InputStream inputStream = responseBody.byteStream();
  try {
    byte[] buffer = new byte[MAX_CHUNK_SIZE_BETWEEN_FLUSHES];
    int read;
    while ((read = inputStream.read(buffer)) != -1) {
      ResponseUtil.onIncrementalDataReceived(
        eventEmitter,
        requestId,
        streamDecoder.decodeNext(buffer, read),
        totalBytesRead,
        contentLength);
    }
  } finally {
    inputStream.close();
  }
}
 
Example #21
Source File: LocationModule.java    From react-native-GPay with MIT License 4 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
  getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class)
      .emit("geolocationDidChange", locationToMap(location));
}
 
Example #22
Source File: LocationModule.java    From react-native-GPay with MIT License 4 votes vote down vote up
private void emitError(int code, String message) {
  getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class)
      .emit("geolocationError", PositionError.buildError(code, message));
}
 
Example #23
Source File: AppStateModule.java    From react-native-GPay with MIT License 4 votes vote down vote up
private void sendAppStateChangeEvent() {
  getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class)
          .emit("appStateDidChange", createAppStateEventMap());
}
 
Example #24
Source File: NetworkingModuleTest.java    From react-native-GPay with MIT License 4 votes vote down vote up
@Test
public void testSuccessfulPostRequest() throws Exception {
  RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class);
  ReactApplicationContext context = mock(ReactApplicationContext.class);
  when(context.getJSModule(any(Class.class))).thenReturn(emitter);

  OkHttpClient httpClient = mock(OkHttpClient.class);
  when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          Call callMock = mock(Call.class);
          return callMock;
        }
      });
  OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class);
  when(clientBuilder.build()).thenReturn(httpClient);
  when(httpClient.newBuilder()).thenReturn(clientBuilder);
  NetworkingModule networkingModule = new NetworkingModule(context, "", httpClient);

  JavaOnlyMap body = new JavaOnlyMap();
  body.putString("string", "This is request body");

  mockEvents();
  
  networkingModule.sendRequest(
    "POST",
    "http://somedomain/bar",
    0,
    JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "text/plain")),
    body,
    /* responseType */ "text",
    /* useIncrementalUpdates*/ true,
    /* timeout */ 0,
    /* withCredentials */ false);

  ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
  verify(httpClient).newCall(argumentCaptor.capture());
  assertThat(argumentCaptor.getValue().url().toString()).isEqualTo("http://somedomain/bar");
  assertThat(argumentCaptor.getValue().headers().size()).isEqualTo(2);
  assertThat(argumentCaptor.getValue().method()).isEqualTo("POST");
  assertThat(argumentCaptor.getValue().body().contentType().type()).isEqualTo("text");
  assertThat(argumentCaptor.getValue().body().contentType().subtype()).isEqualTo("plain");
  Buffer contentBuffer = new Buffer();
  argumentCaptor.getValue().body().writeTo(contentBuffer);
  assertThat(contentBuffer.readUtf8()).isEqualTo("This is request body");
}
 
Example #25
Source File: ApplicationActivity.java    From react-native-turbolinks with MIT License 4 votes vote down vote up
protected RCTDeviceEventEmitter getEventEmitter() {
    return getReactInstanceManager().getCurrentReactContext().getJSModule(RCTDeviceEventEmitter.class);
}
 
Example #26
Source File: NetworkingModule.java    From react-native-GPay with MIT License 4 votes vote down vote up
private RCTDeviceEventEmitter getEventEmitter() {
  return getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class);
}
 
Example #27
Source File: NetworkingModule.java    From react-native-GPay with MIT License 4 votes vote down vote up
private @Nullable MultipartBody.Builder constructMultipartBody(
    ReadableArray body,
    String contentType,
    int requestId) {
  RCTDeviceEventEmitter eventEmitter = getEventEmitter();
  MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
  multipartBuilder.setType(MediaType.parse(contentType));

  for (int i = 0, size = body.size(); i < size; i++) {
    ReadableMap bodyPart = body.getMap(i);

    // Determine part's content type.
    ReadableArray headersArray = bodyPart.getArray("headers");
    Headers headers = extractHeaders(headersArray, null);
    if (headers == null) {
      ResponseUtil.onRequestError(
        eventEmitter,
        requestId,
        "Missing or invalid header format for FormData part.",
        null);
      return null;
    }
    MediaType partContentType = null;
    String partContentTypeStr = headers.get(CONTENT_TYPE_HEADER_NAME);
    if (partContentTypeStr != null) {
      partContentType = MediaType.parse(partContentTypeStr);
      // Remove the content-type header because MultipartBuilder gets it explicitly as an
      // argument and doesn't expect it in the headers array.
      headers = headers.newBuilder().removeAll(CONTENT_TYPE_HEADER_NAME).build();
    }

    if (bodyPart.hasKey(REQUEST_BODY_KEY_STRING)) {
      String bodyValue = bodyPart.getString(REQUEST_BODY_KEY_STRING);
      multipartBuilder.addPart(headers, RequestBody.create(partContentType, bodyValue));
    } else if (bodyPart.hasKey(REQUEST_BODY_KEY_URI)) {
      if (partContentType == null) {
        ResponseUtil.onRequestError(
          eventEmitter,
          requestId,
          "Binary FormData part needs a content-type header.",
          null);
        return null;
      }
      String fileContentUriStr = bodyPart.getString(REQUEST_BODY_KEY_URI);
      InputStream fileInputStream =
          RequestBodyUtil.getFileInputStream(getReactApplicationContext(), fileContentUriStr);
      if (fileInputStream == null) {
        ResponseUtil.onRequestError(
          eventEmitter,
          requestId,
          "Could not retrieve file for uri " + fileContentUriStr,
          null);
        return null;
      }
      multipartBuilder.addPart(headers, RequestBodyUtil.create(partContentType, fileInputStream));
    } else {
      ResponseUtil.onRequestError(eventEmitter, requestId, "Unrecognized FormData part.", null);
    }
  }
  return multipartBuilder;
}
 
Example #28
Source File: RNCallKeepModule.java    From react-native-callkeep with ISC License 4 votes vote down vote up
private void sendEventToJS(String eventName, @Nullable WritableMap params) {
    this.reactContext.getJSModule(RCTDeviceEventEmitter.class).emit(eventName, params);
}