Skip to content

Instantly share code, notes, and snippets.

@joshjhargreaves
Last active September 7, 2018 04:05
Show Gist options
  • Save joshjhargreaves/b0d3f92e05d06d2dd3d6609698621641 to your computer and use it in GitHub Desktop.
Save joshjhargreaves/b0d3f92e05d06d2dd3d6609698621641 to your computer and use it in GitHub Desktop.
Consuming Blobs in a Native Module in React Native

Blob support landed in React Native in 0.54.

In effect this means you can hold a reference in JS to a resource which exists on the native side, and pass it to a native module without needing a round trip of the serialised data over the bridge and back.

JS side, you can retrieve a blob from fetch like so, which you can then pass to your native module.

const response = await fetch(BLOB_URL);
const blob = await response.blob();
...
blob.clear();

After the blob has been used (on the native side), you must call blob.clear() to release the native memory to avoid leaks. This may mean that you need to wait for any native module code you pass the blob to to finish executing before you clear the memory. As native module calls are Promise based, you may need to await the success/failure of your native module call before you call clear().

You can consume a blob in a native module like so (the first arg is a blob):
(Android): https://github.com/facebook/react-native/blob/5c2720b089dd0fb277771b0ac8b0e7788c493e5d/ReactAndroid/src/main/java/com/facebook/react/modules/blob/FileReaderModule.java#L39
(iOS): https://github.com/facebook/react-native/blob/master/Libraries/Blob/RCTFileReaderModule.m#L23

As shown in the above examples, with your blob as an argument to your native module, you can consume the blob by using the respective (BlobModule|RCTBlobManager)#resolve methods and receive a NSData pointer (iOS) or Byte Array (Android) which we can do what we want with (write to a file for example).

On Android we could write the the Byte Array to a file like so from our native module:

FileOutputStream fos = getReactContext().openFileOutput("FILENAME", Context.MODE_PRIVATE);

fos.write(data);

fos.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment