Skip to content

Instantly share code, notes, and snippets.

@earthflower
Last active January 23, 2023 21:35
Show Gist options
  • Save earthflower/8c42ff1f66ec702dce03e4c96b59d2f9 to your computer and use it in GitHub Desktop.
Save earthflower/8c42ff1f66ec702dce03e4c96b59d2f9 to your computer and use it in GitHub Desktop.
react-native-webview-rxjs-context.js
import React, { useState, createContext } from 'react';
import { WebView } from 'react-native-webview';
import { fromEvent } from 'rxjs';
import { map, filter, take } from 'rxjs/operators';
const ResultContext = createContext();
const WebViewContext = createContext();
function MyComponent() {
const [result, setResult] = useState(null);
const handleMessage = async (event) => {
// create observables for different events
const add$ = fromEvent(event, 'message').pipe(
filter(e => e.nativeEvent.data.type === 'add'),
map(e => e.nativeEvent.data.value),
take(1)
);
const subtract$ = fromEvent(event, 'message').pipe(
filter(e => e.nativeEvent.data.type === 'subtract'),
map(e => e.nativeEvent.data.value),
take(1)
);
// subscribe to the observables and wait for the next message
try {
const addValue = await add$.toPromise();
const subtractValue = await subtract$.toPromise();
setResult(addValue - subtractValue);
} catch (e) {
console.error(e);
}
}
return (
<ResultContext.Provider value={result}>
<WebViewContext.Provider value={webviewRef}>
<WebView onMessage={handleMessage} source={{ uri: 'https://example.com' }} />
<button onPress={() => webviewRef.current.postMessage({ type: 'add', value: 10 })}>
Add 10
</button>
</WebViewContext.Provider>
</ResultContext.Provider>
);
}
const webviewRef = React.createRef();
export { MyComponent, ResultContext, WebViewContext };
@earthflower
Copy link
Author

In this example, I added a button that when pressed will call a method postMessage on the webView ref, by passing an object with type and value, which will trigger the add method in the webView

Please note that this code is just a sample and has not been tested. It's a good starting point but you may need to make adjustments to match your use case.
It also assumes that the message received from webView has structure of {type: 'add'|'subtract', value: number}
It also assumes that the webView has implemented an add method that can handle the message sent from the app.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment