parallel execution of multiple methods - on_navigate taipy

46 Views Asked by At

is it possible for parallel execution of methods in the on_navigate? I tried ThreadPoolExecutor but showed an error Working outside of the application context.

def on_navigate(state: State, page_name: str) -> str:
    page_actions = {
        "Overview": [update_total_projects],
        "Create": [create_update_available_projects],
        "Edit": [refresh_edit_page_elements, edit_update_available_projects],
        "Live": [live_update_available_projects, update_available_Machines,
                 update_available_Materials, update_available_Materials_Matrix, update_available_Materials_dis,
                 update_available_Applicators, update_available_nozzle_s, update_available_nozzle_d, update_available_nozzle_l]
    }
1

There are 1 best solutions below

3
Florian Jacta On

Two solutions exist to simplify the use of thread and avoid these issues. You can either use:

  • invoke_callback: you can use it inside a Thread and use the State inside your function.

  • invoke_long_callback: is using the invoke_callback behind the scene to create a simpler syntax to make asynchronous calls.

Here are some examples of code (Taipy 3.0):

For invoke_long_callback:

from taipy.gui import Gui, State, get_state_id, notify, invoke_callback
from threading import Thread


gui = Gui(pages={"/":"<|navbar|>", "page1":"page1", "page2":"page2"})

def heavy_function_done(state: State):
    # Now the State can be used to update the user interface
    notify(state, "info", "The task was done!")

def heavy_function_in_thread(state_id: str):
    invoke_callback(gui, state_id, heavy_function_done, [])

def on_navigate(state: State, page_name: str) -> str:
    thread = Thread(target=heavy_function_in_thread,
                    args=[get_state_id(state)])
    thread.start()
    return page_name
    
gui.run()

For invoke_long_callback:

from taipy.gui import Gui, State, notify, invoke_long_callback

def heavy_function_done(state: State):
    # Now the State can be used to update the user interface
    notify(state, "info", "The task was done!")

def iddle():
    # Function without the state that can give results
    pass

def on_navigate(state: State, page_name: str) -> str:
    invoke_long_callback(state, iddle, [],
                         heavy_function_done, [])
    return page_name
    
Gui(pages={"/":"<|navbar|>", "page1":"page1", "page2":"page2"}).run()