Search code examples
c#blazor.net-5blazor-jsinterop

Blazor, run non static function when static string change


I'm having a static class with a static string, this string are changed by a Javascript. What is the best way to check for changes of this string in a (non-static) blazor component?

I can have a function run on a timer and let that notify me when a change is made, what other options do I have here?

the function that needs to know if the static string has changed are present in a component that inherits from ComponentBase, if thats any help.


Solution

  • Just to mention that you can invoke an instance .Net method by utilizing Blazor JavaScript interop, have a look at the following MS documentation.

    But to answer your question, as Robert pointed in a comment, using the observer pattern or a simple Event can satisfy your need:

    static class MyStaticClass
    {
        public static EventHandler<string> MyPropertyChanged;
    
        private static string _myProperty;
        public static string MyProperty
        {
            get => _myProperty;
            set
            {
                if (_myProperty != value)
                {
                    _myProperty = value;
                    MyPropertyChanged?.Invoke(typeof(MyStaticClass), _myProperty);
                }
            }
        }
    }
    

    And then you can subscribe to this event in your non static class:

    public class MyClass
    {
        public MyClass()
        {
            MyStaticClass.MyPropertyChanged += MyPropertyChanged;
        }
    
        private void MyPropertyChanged(object sender, string e)
        {
            Console.WriteLine($"Changed value is {e}");
        }
    }
    

    But the problem with subscribing to a static class event will be the potential memory leak if your MyClass instance does not live throughout the app's life cycle, while the static event is. Have a look at Jon Skeet's explanation on this. You can try unsubscribing from the event when you are done with the MyClass instance. Additionally, for a Blazor component, have a look at Component disposal with IDisposable and IAsyncDisposable where you might be able to unsubscribe in the component disposal. You can also try implementing Weak Event Pattern to overcome this issue.