目录

Running or Stopping an Event Loop in an Asynchronous Thread Using Node-API Extension APIs

Scenario

When calling asynchronous ArkTS APIs in the ArkTS running environment, you can use napi_run_event_loop to run an event loop and use napi_stop_event_loop to stop an event loop.

Example

If asynchronous ArkTS APIs are called, you can use napi_run_event_loop to run the events in the asynchronous thread cyclically. The underlying asynchronous tasks in the event queue will be processed based on the event loop mode. Currently, Node-API provides two modes for running event loops: napi_event_mode_nowait and napi_event_mode_default.

If napi_event_mode_nowait is used, the current asynchronous thread will not be blocked while the system attempts to process a task in the underlying event queue. After the task is complete, the event loop stops. If there is no task in the event queue, the event loop stops immediately.

If napi_event_mode_default is used, the system blocks the current asynchronous thread and keeps trying to obtain tasks from the event queue and execute these tasks. If you do not want the current thread to be blocked, use napi_stop_event_loop to stop the event loop.

[h2]Sample Code

  1. Configure the CMakeLists.txt file as follows:

    // CMakeLists.txt
    # the minimum version of CMake.
    cmake_minimum_required(VERSION 3.5.0)
    project(MyApplication3)
    
    set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
    
    if(DEFINED PACKAGE_FIND_FILE)
        include(${PACKAGE_FIND_FILE})
    endif()
    add_definitions( "-DLOG_TAG=\"LOG_TAG\"" )
    include_directories(${NATIVERENDER_ROOT_PATH}
                        ${NATIVERENDER_ROOT_PATH}/include)
    
    add_library(entry SHARED napi_init.cpp)
    target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so)
  2. Add the following to the build-profile.json5 file of the module.

      "buildOption": {
        "arkOptions" : {
          "runtimeOnly" : {
            "sources": [
              "./src/main/ets/pages/ObjectUtils.ets"
            ]
          }
        },
    // ...
      },