sindresorhus / KeyboardShortcuts

⌨️ Add user-customizable global keyboard shortcuts (hotkeys) to your macOS app in minutes
https://swiftpackageindex.com/sindresorhus/KeyboardShortcuts/documentation/keyboardshortcuts/keyboardshortcuts
MIT License
1.94k stars 181 forks source link

How to update trigger function? #178

Closed tuanphamanh91 closed 2 months ago

tuanphamanh91 commented 2 months ago

Hello, I initially registered an event handler for the keydown event to execute function1 as follows:

KeyboardShortcuts.onKeyDown(for: shortcut.keyboardShortcut) {
    function1()
}

Now, I want to update it to only call function2:

KeyboardShortcuts.onKeyDown(for: shortcut.keyboardShortcut) {
    function2()
}

However, when the keyboard is triggered, both function1 and function2 are being called. What should I do to resolve this issue? Thank you.

sindresorhus commented 2 months ago

You could use a conditional:

KeyboardShortcuts.onKeyDown(for: shortcut.keyboardShortcut) {
    if shouldCallFunc1 {
        function1()
    } else {
        function2()
    }
}

But a better solution would be to use https://swiftpackageindex.com/sindresorhus/keyboardshortcuts/2.0.1/documentation/keyboardshortcuts/keyboardshortcuts/events(_:for:), where you can easily unsubscribe as it's just an async sequence.

KeyboardShortcuts.onKeyDown is a legacy method and will eventually be deprecated when async sequences in Swift are more mature.

tuanphamanh91 commented 2 months ago

I still can not figure it. Could you please give me an example of using https://swiftpackageindex.com/sindresorhus/keyboardshortcuts/2.0.1/documentation/keyboardshortcuts/keyboardshortcuts/events(_:for:) to register and update the trigger function. Thank you so much!

sindresorhus commented 2 months ago

That would be better asked on Stack Overflow, as it's not specific to this package, but rather is about how to use async sequences in general. But in short, create a Task, store a reference to the task, iterate over the async sequence in the task, and when you want to end it, call .cancel() on the Task.