带有resultSelector的RxSwift withLatestFrom无法编译

时间:2019-05-10 07:20:12

标签: swift rx-swift rx-cocoa

我有一个Driver类型的Bool和一个BehaviorRelay类型的Page(这是一个自定义枚举)。

enum Page {
    case option1(CustomClass1, CustomClass2)
    case option2(CustomClass3)
    case option3(CustomClass4)

    var property1: CustomClass2? {
        switch self {
        case .option1(_, let custom):
            return custom
        case .option2, .option3:
            return nil
        }
    }
}

我在另一个ViewModel中有Driver<Bool>

class ViewModel1 {
    struct Output {
        let hasItems: Driver<Bool>
    }

    let output: Output

    init() {
        let hasItemsRelay: BehaviorRelay<Bool> = BehaviorRelay<Bool>(value: false)

        self.output = Output(
            hasItems: hasItemsRelay.asDriver()
        )
    }
}

我的基类中有一个BehaviorRelay<Page?>

class ViewModel2 {
    let currentPageRelay: BehaviorRelay<Page?> = BehaviorRelay<Page?>(value: nil)

    init() {
        self.currentPageRelay = BehaviorRelay<Page?>(value: nil)
    }
}

ViewModel2类中,我试图在hasItems的{​​{1}}驱动程序上捕获一个事件,当我得到一个事件时,我需要ViewModel1.Input的当前值然后再做些事。所以基本上currentPageRelay是我需要使用的东西。

withLatestFrom

Xcode在class ViewModel2 { private func test() { let customViewModel: ViewModel1 = ViewModel1() customViewModel .output .hasItems .withLatestFrom(currentPageRelay) { ($0, $1) } .map { (hasItems, page) -> (CustomClass2, Bool)? in guard let property1 = page?.property1 else { return nil } return (property1, hasItems) } .unwrap() .drive(onNext: { (property1, hasItems) in // do stuff } .disposed(by: disposeBag) } } 上完全丢失了它。没有代码完成,并且出现以下编译错误: withLatestFrom

我完全不知道这件事。我已经尝试了所有方法,并在其下面的参数列表中提供了正确的类,以便它知道会发生什么,但到目前为止还算不上运气。

1 个答案:

答案 0 :(得分:2)

.asObservable()之后添加.hasItems

class ViewModel2 {
    let currentPageRelay: BehaviorRelay<Page?> = BehaviorRelay<Page?>(value: nil)
    let disposeBag = DisposeBag()

    init() {
        // self.currentPageRelay = BehaviorRelay<Page?>(value: nil)
    }

    private func test() {
        let customViewModel: ViewModel1 = ViewModel1()

        customViewModel
            .output
            .hasItems
            .asObservable()
            .withLatestFrom(currentPageRelay) { ($0, $1) }
            .map { (hasItems, page) -> (CustomClass2, Bool)? in
                guard let property1 = page?.property1 else { return nil }
                return (property1, hasItems)
            }
            .asDriver(onErrorJustReturn: nil)
            .drive(onNext: {
                guard let (property1, hasItems) = $0 else {
                    return
                }
                // do stuff
            })
            .disposed(by: disposeBag)
    }
}