Called multiple times

Eduardo Gomez Romero 1,175 Reputation points
2025-01-14T16:59:23.9566667+00:00

I have a turbine service that fetches data from a database, obviously I check for internet

 public event Action NoInternet = delegate { };
 private const string collectionName = AppConstants.COLLECTIONNAME;
 private readonly IFirestoreService _firestoreService;
 private readonly IBlobService _blobService;
 private readonly IConnectivity _connectivity;
 private static Timer? _timer;
 private FirestoreDb? _firestoreDb;
 private IPinClickHandler? _pinClickHandler;
 private bool isInitializing = false;
 public ICommand PinClickedCommand { get; private set; } = null!;
 public ObservableCollection<TurbinePin> TurbinePins { get; set; } = [];
 public TurbinesService(IFirestoreService firestoreService, IBlobService blobService, IConnectivity connectivity)
 {
     _firestoreService = firestoreService;
     _blobService = blobService;
     _connectivity = connectivity;
     AssingCommand();
 }
 private void AssingCommand()
 {
     PinClickedCommand = new Command<TurbinePin>(async (pin) =>
     {
         if (_pinClickHandler != null)
         {
             await _pinClickHandler.PinMarkerClicked(pin);
         }
     });
 }
 public async Task InitializeAsync()
 {
     if (isInitializing)
     {
         return; // Prevent multiple initializations
     }
     isInitializing = true;
     TurbinePins.Clear();
     try
     {
         if (_connectivity.NetworkAccess != NetworkAccess.Internet)
         {
             NoInternet?.Invoke();
             isInitializing = false;
             return;
         }
         bool isInitialized = await _firestoreService.InitializeFirestoreAsync();
         if (isInitialized)
         {
             _firestoreDb = _firestoreService.GetFirestoreDb();
             if (_firestoreDb != null)
             {
                 await LoadOrInitializeTurbineAsync();
                 //InitializeTimer();
             }
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine($"Initialization failed: {ex.Message}");
     }
     finally
     {
         isInitializing = false;
     }
 }

in the appshellviewmodel, I check if the connection has changed, in order to show a pop up

        public AppShellViewModel(ITurbineService turbineService, IAppService appService,
            IServiceProvider serviceProvider, ICommandHandler commandHandler,
            IConnectivity connectivity, NoInternetPopUp noInternetPopUp)
        {
            _serviceProvider = serviceProvider;
            _turbineService = turbineService;
            _appService = appService;
            _commandHandler = commandHandler;
            _connectivity = connectivity;
            _noInternetPopUp = noInternetPopUp;
            _turbineService.NoInternet += TurbineService_NoInternet;
            InitializeCommand();
            _turbineService.SetPinClickHandler(this);
            _connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
        }
        private void TurbineService_NoInternet()
        {
            _noInternetPopUp.Show();
        }
        private void InitializeCommand()
        {
            _commandHandler.SetPinClickedCommand(new Command<TurbinePin>(async (pin) =>
            await PinMarkerClicked(pin)));
        }
        [RelayCommand]
        async Task Appearing(AppShell appShell)
        {
            _shell = appShell;
            try
            {
                if (TurbinePins.Count == 0 && !isInitializing)
                {
                    isInitializing = true;
                    await _turbineService.InitializeAsync();
                    isInitializing = false;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Initialization failed: {ex.Message}");
                isInitializing = false;
            }
        }
        private void Connectivity_ConnectivityChanged(object? sender, ConnectivityChangedEventArgs e)
        {
            HandleConnectivityChangeAsync();
        }
        private async void HandleConnectivityChangeAsync()
        {
            if (_connectivity.NetworkAccess == NetworkAccess.Internet)
            {
#if WINDOWS
               Debug.WriteLine("Connected");
               WeakReferenceMessenger.Default.Send("CONNECTED");
#endif
                _noInternetPopUp.IsOpen = false;
                try
                {
                    if (TurbinePins.Count == 0 && !isInitializing)
                    {
                        isInitializing = true;
                        await _turbineService.InitializeAsync();
                        isInitializing = false;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Initialization failed: {ex.Message}");
                    isInitializing = false;
                }
            }
            else
            {
                TurbineService_NoInternet();
            }
        }

the problem is that the method is getting called multiple times

for example, if you run the app without internet and turn the internet on, this is 1 change, but is being called more times

https://reccloud.com/u/9c23kk1

therefore, if I send a message or whatever to another page, I receive it 6 times

        private async void HandleConnectivityChangeAsync()
        {
            if (_connectivity.NetworkAccess == NetworkAccess.Internet)
            {
#if WINDOWS
               WeakReferenceMessenger.Default.Send("CONNECTED");
#endif
                _noInternetPopUp.IsOpen = false;
                try
                {
                    if (TurbinePins.Count == 0 && !isInitializing)
                    {
                        isInitializing = true;
                        await _turbineService.InitializeAsync();
                        isInitializing = false;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Initialization failed: {ex.Message}");
                    isInitializing = false;
                }
            }
            else
            {
                TurbineService_NoInternet();
            }
        }

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,814 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.