Logo video2dn
  • Сохранить видео с ютуба
  • Категории
    • Музыка
    • Кино и Анимация
    • Автомобили
    • Животные
    • Спорт
    • Путешествия
    • Игры
    • Люди и Блоги
    • Юмор
    • Развлечения
    • Новости и Политика
    • Howto и Стиль
    • Diy своими руками
    • Образование
    • Наука и Технологии
    • Некоммерческие Организации
  • О сайте

Скачать или смотреть Understanding Why the onReceive(...) Method is Called Twice in SwiftUI Code

  • vlogize
  • 2025-07-26
  • 8
Understanding Why the onReceive(...) Method is Called Twice in SwiftUI Code
Why is the method onReceive(...) being called twice in this piece of code?iosswiftswiftui
  • ok logo

Скачать Understanding Why the onReceive(...) Method is Called Twice in SwiftUI Code бесплатно в качестве 4к (2к / 1080p)

У нас вы можете скачать бесплатно Understanding Why the onReceive(...) Method is Called Twice in SwiftUI Code или посмотреть видео с ютуба в максимальном доступном качестве.

Для скачивания выберите вариант из формы ниже:

  • Информация по загрузке:

Cкачать музыку Understanding Why the onReceive(...) Method is Called Twice in SwiftUI Code бесплатно в формате MP3:

Если иконки загрузки не отобразились, ПОЖАЛУЙСТА, НАЖМИТЕ ЗДЕСЬ или обновите страницу
Если у вас возникли трудности с загрузкой, пожалуйста, свяжитесь с нами по контактам, указанным в нижней части страницы.
Спасибо за использование сервиса video2dn.com

Описание к видео Understanding Why the onReceive(...) Method is Called Twice in SwiftUI Code

Learn why the `onReceive(...)` method is triggered multiple times in SwiftUI and explore the solution to avoid this problem with stored properties and view models.
---
This video is based on the question https://stackoverflow.com/q/67875966/ asked by the user 'AlanSTACK' ( https://stackoverflow.com/u/3810748/ ) and on the answer https://stackoverflow.com/a/67876070/ provided by the user 'jnpdx' ( https://stackoverflow.com/u/560942/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Why is the method onReceive(...) being called twice in this piece of code?

Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l...
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license.

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---
Understanding Why the onReceive(...) Method is Called Twice in SwiftUI Code

If you're diving into iOS programming and using SwiftUI, you might encounter some perplexing behavior with your UI components. For instance, you may find that the onReceive(...) callback method is being triggered twice when you interact with a toggle. This issue can be confusing for newcomers and can disrupt the expected functionality of your app. Let's explore this issue together and understand the root cause, along with a solution.

The Problem: Duplicate onReceive(...) Calls

Consider this scenario: you have two toggle switches in your SwiftUI application, and each toggle triggers a print() statement upon being toggled. Here's a simplified version of your code:

[[See Video to Reveal this Text or Code Snippet]]

Expected Output

When interacting with the first toggle, you would expect to see:

[[See Video to Reveal this Text or Code Snippet]]

However, what you observe instead is that both toggle callbacks are firing at the same time:

[[See Video to Reveal this Text or Code Snippet]]

The Cause: View Re-rendering

This unexpected output can be traced back to the way SwiftUI handles view re-rendering. Every time a @ State variable (like listener_toggle_1) is modified, SwiftUI re-renders the entire view. When you create your publishers using the line [self.listener_toggle_1].publisher.first(), new instances of these publishers are generated every time the view is re-rendered. As a result, both publishers fire the corresponding callbacks, causing the output to appear twice.

The Solution: Use a View Model with @ Published Properties

To resolve this duplicate triggering of the onReceive(...) callback, you can store your toggle properties in a view model that uses @ Published properties. This approach ensures that the properties persist correctly between re-renders without recreating the publishers each time. Here's how to implement this solution:

Step 1: Create a View Model

First, create a ViewModel class that conforms to ObservableObject:

[[See Video to Reveal this Text or Code Snippet]]

Step 2: Implement the View Model in Your View

Now, adjust your ContentView to use the ViewModel to manage the toggle states:

[[See Video to Reveal this Text or Code Snippet]]

Summary of Changes

Utilize a ViewModel class to manage state.

Replace @ State properties with @ Published properties in the ViewModel.

Use @ StateObject in your view to hold your ViewModel instance.

Conclusion

By using a view model with @ Published properties, you can effectively prevent the onReceive(...) method from firing more than once due to unnecessary view re-renders. This approach not only improves the performance of your SwiftUI app but also leads to cleaner, more maintainable code. If you're just starting with iOS programming, mastering these concepts will set you on a path to building robust applications. Happy coding!

Комментарии

Информация по комментариям в разработке

Похожие видео

  • О нас
  • Контакты
  • Отказ от ответственности - Disclaimer
  • Условия использования сайта - TOS
  • Политика конфиденциальности

video2dn Copyright © 2023 - 2025

Контакты для правообладателей [email protected]