Force show spinner (opposite of anvil.server.no_loading_indicator)

There are use cases for showing the spinner manually (grouping a load of short calls into one spin cycle, for example) that can’t be performed currently - would it be possible to add a context manager similar to no_loading_indicator to force a loading indicator? TIA

4 Likes

I am a bit confused, is it for client side calls, isn’t it? Since all server calls have the spinner

what a great idea.

Here’s a demo of how to do it.

https://anvil.works/build#clone:QELJIOSD62ZWIULK=BK6RBPA5BK7M76YFSGNUO2MG

the end user code:

  def button_1_click(self, **event_args):
    """This method is called when the button is clicked"""
    with loading_indicator:
      from time import sleep
      sleep(3)

WmXgZH9dpi

the code to make it work

import anvil as _anvil

class _loading_indicator:
  def __enter__(self):
    _anvil.js.call_js('setLoading', True)
    return self
  def __exit__(self, exc_type, exc_value, tb):
    _anvil.js.call_js('setLoading', False)

loading_indicator = _loading_indicator()

# setLoading is the javascript function anvil uses to turn the loading indicator on and off
# I guess it's not part of the docs so can't be relied upon...

You could also extend it to be a decorator for a function if you wanted… but since you request a context manager…

11 Likes

This is perfect! Thanks! I might try extending that to work as a decorator for people who come across this thread, actually…

3 Likes

I have successfully implemented the decorator functionality:

https://anvil.works/build#clone:HO4BCOPJPAIHXBO5=5XNINH6RDK4W46IYON6BPT46

Code:

import anvil as _anvil
# from functools import wraps

class _loading_indicator:
    def __enter__(self):
        _anvil.js.call_js('setLoading', True)
        return self
    def __exit__(self, exc_type, exc_value, tb):
        _anvil.js.call_js('setLoading', False)
    def __call__(self, func):
#         @wraps(func)
        def wrapper(*args, **kw):
            with self:
                return func(*args, **kw)
        return wrapper

loading_indicator = _loading_indicator()
7 Likes

A post was split to a new topic: Spinner control