【问题标题】:ReactiveCocoa 4 MVVM best practice with HTTP requests带有 HTTP 请求的 ReactiveCocoa 4 MVVM 最佳实践
【发布时间】:2015-12-02 06:52:02
【问题描述】:

我正在开发我的应用程序的登录部分,我想使用 ReactiveCocoa 4。:)

这是我认为的初始化:

self.viewModel.loginSignal = self.LoginButton.rac_signalForControlEvents(UIControlEvents.TouchUpInside)!

self.viewModel.loginStatus.producer.startWithNext({ status in
  self.setLoginButtonStatus(status)
})

self.viewModel.initSignals()

setLoginButtonStatus 只会禁用/启用按钮等,而status 只是一个枚举。

这是在我的视图模型的initSignals()

self.loginSignal!.toSignalProducer().start({ sender in
  self.validateLoginInput()
})

其中loginSignal 被声明为var loginSignal: RACSignal?

这是我的validateLoginInput

self.loginStatus.value = MyStatus.Login.IN_PROGRESS // So button would be disabled

session.rac_dataWithRequest(request).map({ data, response in
  return MyResponse(data, response)
}).startWithNext({ response
  // Say MyResponse class would check the reponse if login is successful
  if response.isSuccessful() {
    self.loginStatus.value = MyStatus.Login.SUCCESS
  } else {
    self.loginStatus.value = MyStatus.Login.FAIL
  }
})

视图应该首先禁用按钮,然后在会话结束和response.isSuccessful() 为真时重新启用它。

好吧,它现在可以工作,但我想知道我是否正在适当地使用带有 ReactCocoa 4 的 MVVM。

另外,我收到了一个让我有点困扰的“警告”。这看起来就像 HTTP 请求得到响应后的一秒钟。

2015-12-02 12:15:32.566 MyProject[460:48610] This application is
modifying the autolayout engine from a background thread, which can
lead to engine corruption and weird crashes.  This will cause an
exception in a future release.

是因为我在Swift 2.1 上使用了v4.0.0-alpha.4这实际上延迟了我的按钮的重新启用

我对网络上的示例感到困惑,因为它们中的大多数都在 Objective-C 中,而且我认为某些函数名称已更改,等等...

非常感谢!

【问题讨论】:

    标签: swift mvvm swift2 ios9 reactive-cocoa


    【解决方案1】:

    其他人可以谈论您正在采用的 MVVM 方法,但关于您看到的警告:那是因为您正在使用后台线程中的 UIKit。我想这来自self.setLoginButtonStatus 电话。根据您绑定到该属性的信号,有可能(并且在这种情况下正在发生)其生产者发出的值不会在主线程上发出

    要解决这个问题,您可以使用observeOn 将值转发到主线程:

    self.viewModel.loginStatus
        .producer
        .observeOn(UIScheduler())
        .startWithNext { status in
              self.setLoginButtonStatus(status)
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-18
      • 2021-05-07
      • 1970-01-01
      • 2020-11-20
      • 2019-04-26
      • 2012-08-19
      • 2017-03-21
      • 1970-01-01
      相关资源
      最近更新 更多