npm install react-native-multithreading
npx pod-installRequires react-native-reanimated 2.0.1 or later
By "adapting" a function and converting it to a "Shared Value", it was possible to decouple functions from the JS-Runtime (using Reanimated). The JSI library provides an easy to use API to create a new JSI Runtime Instance. Threads are re-used in a Thread-Pool, and Promises are used so results can be awaited.
To simply do expensive calculation on another thread without caring about results, use the spawnThread function:
// JS thread
spawnThread(() => {
'worklet'
// custom thread
// expensive calculation
})
// JS threadThe React-JS Thread will continue execution while the custom thread will run the given function on a custom parallel runtime.
Since spawnThread returns a Promise, you can also await the result. The React-JS Thread will not be blocked and will still be able to continue execution elsewhere (timers, callbacks, ...), while the custom thread runs the given function in a custom parallel runtime.
const result = await spawnThread(() => {
'worklet'
// expensive calculation
return ...
})This example calculates the Fibonacci Number for the given input. This demonstrates expensive calculation, awaiting the result, as well as using values from "outside". (fibonacci function and input are captured into the new thread and therefore immutable.)
const fibonacci = (num: number): number => {
'worklet'
if (num <= 1) return 1
return fibonacci(num - 1) + fibonacci(num - 2)
}
const input = 50
const result = await spawnThread(() => {
'worklet'
console.log(`calculating fibonacci for input: ${input}...`)
const fib = fibonacci(input)
console.log("finished calculating fibonacci!")
return fib
})
console.log(`Fibonacci Result: ${result}`)- At the moment, only iOS is implemented.
- Since the library uses JSI for synchronous native methods access, remote debugging (e.g. with Chrome) is no longer possible. Instead, you should use Flipper.
- All functions you are calling inside a custom thread, must be workletized to truly run on a separate thread. So add the
'worklet'directive at the top of every function you're calling in that thread (including the thread callback itself), and don't forget to install the Reanimated babel plugin.
MIT
- react-native-reanimated for Shared Value adapting, essentially allowing JSI multithreading
- Erik the Coder for the Icon
- You, for appreciating my work
Note: Technically this is not multithreading, but rather multiprocessing.