NimarkoGram Docs
RU
Docs/Background and UI queues

Background and UI queues

Move a file read off the main thread.

On this pageMove a file read out of a tap handlerDeliver the resultTry leaving the screen

Move a file read out of a tap handler

A settings row should respond as soon as the user taps it. Build the path to the preview from Files and cache before queueing work. Capture that path instead of retaining the Android view. The user can leave settings before the read finishes.

Python
from pathlib import Path
from client_utils import run_on_queue
from file_utils import get_cache_dir, read_file
from ui.bulletin import BulletinHelper

def show_preview_size(self, view):
    path = Path(get_cache_dir()) / self.id / "preview.txt"

    def read_preview():
        value = read_file(str(path))
        if value is None:
            BulletinHelper.show_info("Create a preview first")
        else:
            BulletinHelper.show_info(f"Characters: {len(value)}")

    run_on_queue(read_preview)

Attach the method to Text(on_click=self.show_preview_size, text="Check length"). This counts characters in the decoded string. For the byte count, including multibyte characters and line endings, use the file size.

Deliver the result

run_on_queue defaults to the plugin queue. Its second positional argument is the queue name. Use the named delay argument for a delay in milliseconds. The public BulletinHelper.show_info method already schedules its UI work and checks the plugin instance. For a direct Android View update, use android_utils.run_on_ui_thread(fn) and check that the destination view is still attached.

Try leaving the screen

Save “Hello” without a trailing newline and tap Check length. Expect “Characters: 5”. To exercise a delayed callback, temporarily pass delay=1500 to run_on_queue. Tap the row and immediately disable the plugin. The old instance should produce no bulletin. Remove the delay after this check.