问题
I have a React-Native application and I want to use parallel programming (I want to use all of the cores of the tablet).
I tried paralleljs
and hamsters.js
libraries but they were not useful. One doesn't support RN and the other has some issues with Blobs at the moment.
So, I decided to use web-workers. After doing some search on it (from MDN etc), I realized that I might use web workers alone instead of all these libraries. However I can't be 100% sure about it. There are other libraries designed for RN, like react-native-workers, but all has lots of issues.
My question is how to use pure JS code to make use multi-threading and/or parallel programming in a React-Native application? Or is it not possible yet?
回答1:
You can use WebView which will run JS in background thread. Because inside webview, it is another instance of Webkit, so JS running in it won’t block the app UI at all.
Read this blogpost for more detail: https://medium.com/@inkdrop/a-simple-way-to-run-js-in-background-thread-on-react-native-8fff345576da
回答2:
The official says that React Native can implement some kind of native module bridge in order to take advantage of advanced extensions. I am not sure what you want to achieve by using multi-threading and/or parallel programming, but with pure JavaScript, you can do some similar things like them.
For example, this is a kind of parallel programming with JavaScript.
setTimeout(() => {
// One time-consuming logics
});
setTimeout(() => {
// Another time-consuming logics
});
You can also use Promise. It also provide us the way to handle parallel programming easily as well (https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)
However, if you would like to do the read multi-threading, it is not really easy. You will have to write your own extension code which bridges the native code and React Native. Of course, this is not actually a pure JS anymore, but this is the strength of React Native. You can create your own extension to use native modules in JavaScript.
来源:https://stackoverflow.com/questions/46130319/multi-threading-in-react-native