简体   繁体   English

多次回调,而不是迅速使用代理

[英]Multiple Callbacks instead of use Delegates in swift

I am developing an app that have to send commands to a machine. 我正在开发一个必须向计算机发送命令的应用程序。 I know how to use delegates to propagate the response of the commands that I receive in an Input Stream. 我知道如何使用委托来传播在输入流中收到的命令的响应。 But probably is better to use Callbacks for some commands who have to update the UI. 但是对于某些需要更新UI的命令,最好使用Callbacks。

I have searched for a good solution to code this, but I couldn't find it. 我一直在寻找一个很好的解决方案来编写此代码,但找不到。

In this code, for example: 在此代码中,例如:

class NetworkService {

    var onComplete: ((result: String)->())? //an optional function

    func fetchDataFromUrl(url: String) {
        API.request(.GET, url) { result in
            onComplete?(result: result) 
    }
}

class MyViewController: UIViewController {

    let networkService = NetworkService()

    override func viewDidLoad() {
        super.viewDidLoad()
        networkService.onComplete = { result in
            print("I got \(result) from the server!")
        }
    }
}

It's ok, I can use onComplete as a callback, but... I need multiple callbacks for multiple commands: 可以,我可以将onComplete用作回调,但是...我需要针对多个命令的多个回调:

  • Have I to create a "var" with the callback for each different command? 我是否需要为每个不同的命令的回调创建一个“ var”?
  • Is there a way to have an array or a queue with the callbacks? 有没有一种方法可以使数组或带有回调的队列?
  • What will happen If I don't receive a response for a command, and I send again the command? 如果我没有收到命令的响应,然后再次发送该命令,将会发生什么? I suppose that I have to handle timeouts in some way. 我想我必须以某种方式处理超时。
  • What could be the best way to solve this problem? 解决此问题的最佳方法是什么?

Have you tried notifications? 您是否尝试过通知? on your ViewDidLoad: 在您的ViewDidLoad上:

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(dataFetched), name: NSNotification.Name(rawValue: "dataFetched"), object: nil)
    networkService.fetchDataFromUrl(url: url)
}

func dataFetched(_ notification: Notification) {
    // do your stuff with notification.object
}

on your NetworkService class 在您的NetworkService类上

func fetchDataFromUrl(url: String) { 
    API.request(.GET, url)
}

func dataFetched(result: Any) {
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "dataFetched"), object: result)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM