简体   繁体   中英

Concurrency in Elm

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)

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 .

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 ->
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM