如何在MVVM体系结构中使用RxSwift发送参数以查看模型?

时间:2018-08-03 06:23:09

标签: swift mvvm facebook-ios-sdk rx-swift reactive

我有一种登录到Facebook的服务方法,该方法具有一个类型为View Controller的参数。我使用RxSwift和MVVM。在View Controller中,我绑定了按钮点击以查看模型的观察者,并订阅它以在内部调用服务。如何发送参数视图控制器以查看模型以发送到我的服务?

这正是问题所在

self.authService.signInWithFacebook(来源:???)

class AuthService: AuthServiceType {
 // ...

  func signInWithFacebook(from: UIViewController?) -> Observable<Result<Void, FirebaseLoginError>> {
     // ...
    }

 // ...
}


class LoginViewModel {

    let facebookLoginDidTapObserver: AnyObserver<Void>

    let facebookLoginDidTapObservable: Observable<Void>

    private let authService: AuthServiceType

    init(authService: AuthServiceType = AuthService()) {

        self.authService = authService

        let facebookLoginDidTap = PublishSubject<Void>()
        facebookLoginDidTapObserver = facebookLoginDidTap.asObserver()
        facebookLoginDidTapObservable = facebookLoginDidTap.asObservable()

        facebookLoginDidTapObservable
            .throttle(0.5, scheduler: MainScheduler.instance)
            .subscribe(onNext: { tap in

                return self.authService.signInWithFacebook(from: ???)
            })
            .disposed(by: disposeBag)
    }

}


class LoginViewController: UIViewController {

    facebookLoginButton.rx
        .tap
        .bind(to: viewModel.facebookLoginDidTapObserver)
        .disposed(by: disposeBag) 


} 

1 个答案:

答案 0 :(得分:1)

您可以将VC本身传递给VM,然后公开authService的结果。 最好不要订阅您的VM,因此我也进行了更改。

class LoginViewModel {
  let facebookLoginDidTapObserver: AnyObserver<UIViewController>

  let facebookLoginDidTapObservable: Observable<Result<Void, FirebaseLoginError>>

  private let authService: AuthServiceType

  init(authService: AuthServiceType = AuthService()) {

    self.authService = authService

    let facebookLoginDidTap = PublishSubject<UIViewController>()
    self.facebookLoginDidTapObserver = facebookLoginDidTap.asObserver()

    self.facebookLoginDidTapObservable = facebookLoginDidTap.asObservable()
        .throttle(0.5, scheduler: MainScheduler.instance)
        .flatMapLatest(onNext: { vc in
            return self.authService.signInWithFacebook(from: vc)
        })
  }
}

LoginViewController类:UIViewController {

facebookLoginButton.rx
    .tap
    .map { [unowned self] _ in self }
    .bind(to: viewModel.facebookLoginDidTapObserver)
    .disposed(by: disposeBag) 

}