8

To communicate with Android to ReactNative I use RCTEventEmitter. Using this I need parse array to RN side and this array should set on WritableMap object. On WritableMap object can put Array as shown below,

void putArray(@NonNull String key, @Nullable ReadableArray value);

How to create and add data into ReadableArray ?

E J Chathuranga
  • 927
  • 12
  • 27

2 Answers2

5

I think you're looking for the WritableArray. You can create one like this:

// Initialize an empty array
WritableArray array = new WritableNativeArray();

// Add items to array using its push methods, for example
array.pushString("test");
user56reinstatemonica8
  • 32,576
  • 21
  • 101
  • 125
  • 1
    It's requiring a ReadableArray, and can we cast WritableArray to ReadableArray? – E J Chathuranga Apr 21 '20 at 05:35
  • 1
    The WritableArray extends ReadableNativeArray that implements ReadableArray. You should be able to use this structure without any issues. Also I forgot to give you an example of how to use the WritableArray. You just need to use the push methods like this: ``` array.pushString("test");``` – Fabio Campos Apr 22 '20 at 18:35
1

Arguments from React Native Bridge has a helper method Arguments.fromList(list) that returns a WritableArray, which is a subclass of ReadableArray, so satisfies the condition and is ready to pass to putArray.


For example, to take a list and push it to a JS event as an array property:

Kotlin:

import com.facebook.react.bridge.Arguments
// ...

val params = Arguments.createMap().apply {
   putArray("data", Arguments.fromList(someList))
   // ...put more params
}

Java:

import com.facebook.react.bridge.Arguments;
// ...

WriteableArray array = Arguments.fromList(someList);
WritableMap params = Arguments.createMap();
params.putArray(array);
// ...put more params

Pass these to .emit("SomeEvent", params) and JS should receive { data: [...someList] }.


There's also Arguments.makeNativeArray(list), which has an almost identical API and implementation to .fromList - both create a WritableArray by iterating a list arg, pushing each item by type. The only differences I can see are:

  • .fromList explicitly handles nested arrays
  • .makeNativeArray explicitly handles null (returning an empty array)
user56reinstatemonica8
  • 32,576
  • 21
  • 101
  • 125