Cxx TurboModules > Add example to return a JS function from Cxx to JS (#41385)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41385

Changelog: Internal

Adding a Cxx TM example which adds a listener and returns a subscription to remove that listener from the TM.

You should be able to use this with React Hooks - https://legacy.reactjs.org/docs/hooks-reference.html

E.g.

```
useEffect(() => {
  const subscription =  NativeCxxModuleExample.setValueCallbackWithSubscription(
          callbackValue => // use it
        );
  return subscription;
});
```

Reviewed By: shwanton

Differential Revision: D50473063

fbshipit-source-id: 4e9b92aeccff1771eb4ffad6bdaa20ba7f18435f
This commit is contained in:
Christoph Purrer
2023-11-09 11:38:54 -08:00
committed by Facebook GitHub Bot
parent 01b4d7853d
commit 9320174df4
4 changed files with 33 additions and 0 deletions
@@ -15,6 +15,7 @@
#include <AppSpecs/AppSpecsJSI.h>
#endif
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <vector>
@@ -107,6 +108,10 @@ class NativeCxxModuleExample
jsi::Runtime& rt,
AsyncCallback<std::string> callback);
std::function<void()> setValueCallbackWithSubscription(
jsi::Runtime& rt,
AsyncCallback<std::string> callback);
std::vector<std::optional<ObjectStruct>> getArray(
jsi::Runtime& rt,
std::vector<std::optional<ObjectStruct>> arg);
@@ -169,6 +174,9 @@ class NativeCxxModuleExample
ObjectStruct getObjectAssert(jsi::Runtime& rt, ObjectStruct arg);
AsyncPromise<jsi::Value> promiseAssert(jsi::Runtime& rt);
private:
std::optional<AsyncCallback<std::string>> valueCallback_;
};
} // namespace facebook::react