在多个实例中使用.onReceive代码-SwiftUI

在多个实例中使用.onReceive代码-SwiftUI,swiftui,Swiftui,我有以下代码: VStack { if viewRouter.currentPage == "onboardingView" { OnboardingView() } else if viewRouter.currentPage == "homeView" { TabView { HomeView(meal

我有以下代码:

VStack {
            if viewRouter.currentPage == "onboardingView" {
                OnboardingView()
            } else if viewRouter.currentPage == "homeView" {
                TabView {
                    HomeView(mealsController: self.mealsController)
                        .tabItem {
                            Image(systemName: "house")
                            Text("Menu")
                    }
                    SettingsView(mealsController: self.mealsController)
                        .tabItem {
                            Image(systemName: "slider.horizontal.3")
                            Text("Settings")
                    }
                }
                .accentColor(Color(getThemeConstants.accentThemeColor))
            }
        }
在此基础上,我有:

.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
...
}
.onAppear() {
...
}

.onReceive
内部,我有一堆代码需要在
上重用。onAppear
,我如何重用这种代码?

只需在一些私有函数中提取公共代码,并从两个修饰符调用它,如下所示

.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
   self.handlerFunction()
}
.onAppear() {
   self.handlerFunction()
}

...

private func handlerFunction() {
   // move common code here
}

只需提取一些私有函数中的公共代码,并从两个修饰符中调用它,如下所示

.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
   self.handlerFunction()
}
.onAppear() {
   self.handlerFunction()
}

...

private func handlerFunction() {
   // move common code here
}