How to detect if focused has changed on Mac OS

Is there any API to detect if the focus has changed to other apps on MacOS?

I need to know when is the focus taken and get the top app name so I can clear the floating panels on the last focused app.

Use NSWorkspace.
Here is a simple example:

import SwiftUI

func frontmostApplication() -> String {
    if let w = NSWorkspace.shared.frontmostApplication?.localizedName {
        return w
    return "*Error*"

struct ContentView: View {
    @State var frontApp = frontmostApplication()
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        VStack {
                .onReceive(timer) { input in
                    frontApp = frontmostApplication()

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {