Sync closure needs to wait for async code

I am developing an app that uses MPRemoteCommandCenter to control audio reproduction from the lock screen.

The code is inside a @MainActor view-model, part of a SwiftUI project.

The initial code that I need to incorporate is:

			commandCenter.playCommand.isEnabled = true
			commandCenter.playCommand.addTarget { [unowned self] event in
					if !self.isPlaying {
						self.playOrPause()
						return .success
					}
					return .commandFailed
			}

I have tried this:

			commandCenter.playCommand.isEnabled = true
			commandCenter.playCommand.addTarget { [unowned self] event in
				return await MainActor.run {
					if !self.isPlaying {
						self.playOrPause()
						return .success
					}
					return .commandFailed
				}
			}

But still it doesn't compile.

I understand why: the callback method is not marked to be async. Still it expects a value, that I can return only from async code, because I need to wait to re-enter into the main thread.

Can anyone please help me?

Answered by CuriaDamiano in 751539022

This code works:

		// Add handler for Play Command
		commandCenter.playCommand.addTarget { [unowned self] event in
			if !self.isPlaying {
				self.player.play()
				self.isPlaying = true
				return .success
			}
			return .commandFailed
		}

Accepted Answer

This code works:

		// Add handler for Play Command
		commandCenter.playCommand.addTarget { [unowned self] event in
			if !self.isPlaying {
				self.player.play()
				self.isPlaying = true
				return .success
			}
			return .commandFailed
		}

Sync closure needs to wait for async code
 
 
Q