Skip to content

Instantly share code, notes, and snippets.

@tsapeta
Last active April 28, 2024 20:51
Show Gist options
  • Save tsapeta/deff06b7fffdbcc6912b24cbe9a6ac2c to your computer and use it in GitHub Desktop.
Save tsapeta/deff06b7fffdbcc6912b24cbe9a6ac2c to your computer and use it in GitHub Desktop.
useVideoPlayerVolume vs player.useVolume
// Returns a memoized player instance that updates when the source changes
function useVideoPlayer(source): VideoPlayer {
return useMemo(() => new VideoPlayer(source), [source]);
}
class VideoPlayer extends EventEmitter {
volume: number;
// Hook that updates when its `this` (the player) changes the volume
useVolume(): number {
const [volume, setVolume] = useState(this.volume);
useEffect(() => {
const volumeListener = (newVolume) => setVolume(newVolume);
this.addListener('volumeChange', volumeListener);
return () => {
this.removeListener('volumeChange', volumeListener);
};
});
return volume;
}
}
// Hook that updates when the player given as an argument changes the volume
function useVideoPlayerVolume(player: VideoPlayer): number {
const [volume, setVolume] = useState(player.volume);
useEffect(() => {
const volumeListener = (newVolume) => setVolume(newVolume);
player.addListener('volumeChange', volumeListener);
return () => {
player.removeListener('volumeChange', volumeListener);
};
});
return volume;
}
// Usage
function App() {
const player = useVideoPlayer('https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4');
// Safe with the linter, not very good for DX.
// IntelliSense won't suggest this straight away, you may need to look at the docs.
const volume1 = useVideoPlayerVolume(player);
// Linter can't catch misuses, but it's much easier to discover with IntelliSense,
// assuming that we have more hooks like this on the player.
const volume2 = player.useVolume();
return (
<View>
<Text>useVideoPlayerVolume: {volume1}</Text>
<Text>player.useVolume: {volume2}</Text>
</View>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment