RxSwift + MVVM +协调器模式,如何顺序等待协调器结果?

时间:2018-03-20 10:14:27

标签: swift mvvm reactivex

情景:

我有基本协调员,基本上是这样的:

class Coordinator<Result> {
   // some coordinator class codes

   func coordinate(to: Coordinator<T>) -> Observable<T> {
       return coordinator.start()
   }

   func start() -> Observable<Result> {
      // return result
   }
} 

和TestCoodinator1,TestCoordinator2,TestCoodinator3一样:

enum Status {
    case .success(data: NSData?)
    case .cancelled(error: NSError?)
    case .failed(data: NSData?)
}

class TestCoordinator1: Coordinator<Status> {
     // Init pass UINavigationController as rootViewController

     let testVC1 = TestViewController1()
     let testVM1 = TestViewModel1()
     testVC1.viewModel = testVM1         

     return testVM1.status // returns Observable<Status>
         .do(onNext: { [unowned self] _ in self?.rootViewController.popViewController(animated: true)
} 

我有主协调员,基本上是这样的:

class MainCoordinator: Coordinator<Void> {

    override func start() -> Observable<Void> {
        let mainVC = MainVC()
        let mainVM = MainVM()
        mainVC.viewModel = mainVM

        let testCoordinator1 = TestCoordinator1(in: rootViewController)
        let viewModel1 = ViewModel1()
        testCoordinator1.viewModel = viewModel1

        let testCoordinator2 = TestCoordinator2(in: rootViewController)
        let viewModel2 = ViewModel2()
        testCoordinator2.viewModel = viewModel2

        let testCoordinator3 = TestCoordinator3(in: rootViewController)
        let viewModel3 = ViewModel3()
        testCoordinator3.viewModel = viewModel3

        // viewModel.tests returns Observable that has three types of tests randomly generated
        // Observable.of("Test1", "Test2", "Test3")
        mainVM.tests ????

        return Observable.never()
    }
}

问题:

如何创建observable,其坐标为test1并先等待test1完成,然后对结果进行一些处理,然后只有test2运行,处理一些结果,然后test3运行。

如果我这样做:

mainVM.tests
   .flatMap { test in 
       switch(test) {
           case "Test1":
                 return self.coordinate(to: testCoordinator1)
           case "Test2":
                 return self.coordinate(to: testCoordinator2)
           case "Test3":
                 return self.coordinate(to: testCoordinator3)
       }
   }
   .subscribe(onNext: { status in 
      self.processStatus(status)
   })

所有三个协调员同时运行

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您可以通过chaining observables

实现这一目标
mainVM.tests
    .flatMapLatest { test -> Observable<...> in
        // do some things
        return self.coordinate(to: testCoordinator1)
    }
    .flatMapLatest { _ -> Observable<...> in
        // handle first coordinator
        return self.coordinate(to: testCoordinator2)
    }
    .flatMapLatest { _ -> Observable<...> in
        // handle second coordinator
        return self.coordinate(to: testCoordinator3)
    }
    .flatMapLatest { _ -> Observable<...> in
        // handle third coordinator
    }
    .subscribe(onNext: { status in
        self.processStatus(status)
    })