Reputation: 417
I have a really computationally expensive code that I need to run in my 'update' function.
When it runs, my whole app blocks until it finishes.
Is there any way to run this code asynchronously to prevent the blocking? (while not using ports and staying in elm)
Upvotes: 6
Views: 545
Reputation: 5688
Elm tasks do not support pre-emptive multi-tasking.
With Process.spawn
, you can construct tasks which will context-switch when used as arguments to Task.andThen
.
However, for those, you have to work within the constraint that the resulting task has type Task x Process.Id
, which means there is no easy way to communicate the result of your task back to the main app.
See the documentation for Process.Id
.
Upvotes: 2
Reputation: 9614
You can try to run it as a Task. Tasks can be preemptively be stopped to execute other parts of your application, although I'm unsure how they will work in the case of some using the entirety of the CPU capacity:
DoHeavyStuff a b ->
let
task param1 param2 =
Task.succeed 1
`Task.andThen` (\_ -> Task.succeed <| expensive param1 param2)
in
(model, Task.perform NoOp FinishedWork (task a b))
FinishedWork result ->
...
Upvotes: 0