Created
January 23, 2023 21:58
-
-
Save earthflower/43630023957f8e2b9038df7bfac0a1ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useRef, useContext } from 'react'; | |
import { WebView } from 'react-native-webview'; | |
import { Subject, BehaviorSubject } from 'rxjs'; | |
import { map, tap, filter } from 'rxjs/operators'; | |
const WebViewContext = React.createContext(); | |
function WebViewWrapper() { | |
const webViewRef = useRef(null); | |
const message$ = new Subject(); | |
const result$ = new BehaviorSubject(null); | |
const handleMessage = (event) => { | |
message$.next(event.nativeEvent.data); | |
}; | |
return ( | |
<WebViewContext.Provider value={{ message$, result$ }}> | |
<WebView | |
ref={webViewRef} | |
onMessage={handleMessage} | |
source={{ uri: 'https://example.com' }} | |
/> | |
</WebViewContext.Provider> | |
); | |
} | |
function MyComponent() { | |
const { message$, result$ } = useContext(WebViewContext); | |
message$.pipe( | |
filter((message) => message.type === 'result'), | |
map((message) => message.data), | |
tap((data) => result$.next(data)) | |
).subscribe(); | |
const add = (a, b) => { | |
webViewRef.current.postMessage("add", [a, b]); | |
} | |
const multiply = (a, b) => { | |
webViewRef.current.postMessage("multiply", [a, b]); | |
} | |
return ( | |
<div> | |
<button onClick={() => add(1, 2)}>Add 1 and 2</button> | |
<button onClick={() => multiply(3, 4)}>Multiply 3 and 4</button> | |
<div>{result$.value}</div> | |
</div> | |
); | |
} |
Author
earthflower
commented
Jan 23, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment