2017-04-26 39 views
0

如今我對ReactiveSwift感興趣並嘗試將其添加到項目的聯網動作中。但使用observeResult方法有一些關於動作返回類型的問題。ReactiveSwift動作observeResult不會像它應該返回失敗

視圖模型:

final類TestViewModel:視圖模型{

var getListAction: Action<Void, Void, APIError>! 

var arr = NSMutableArray() 

override init() { 

    super.init() 

    self.getListBuild() 

} 

func getListBuild() { 

    getListAction = Action<Void, Void, APIError> { _ in 
     let signalProducer = SignalProducer<Void, APIError> { observer, disposable in 
      self.getList(observer) 
     } 
     return signalProducer 
    } 

    getListAction.apply().start() 
} 


func getList(_ observer: Observer<Void, APIError>) { 

    Network<UserDetailInfo>().requestList(router: RegistrationRouter(endpoint:.Login())).take(during: lifetime).startWithResult { (result) in 
     switch result { 
     case let .success(value): 
      self.arr = value as! NSMutableArray 
      print("success") 
      observer.sendCompleted() 
     case let .failure(error): 
      print("abort: \(String(describing: error.message))") 
      observer.send(error: error) 
     } 
    } 
} 

}

,並從我試圖去管理這樣的控制器:

最後一類的ViewController:查看{

var viewModel: TestViewModel? 

func bindViewModel() { 

    self.viewModel = TestViewModel() 

    self.viewModel?.getListAction.events.take(during: lifetime).observeResult { (result) in 
     switch result { 
     case .success(_): 
      print("success") 
      print(self.viewModel?.arr.count as Any) 
      break 
     case let .failure(error): 
      print(error.localizedDescription); 
      break 
     } 
    } 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.bindViewModel() 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
} 

}

儘管的GetList方法在視圖模型,像這樣的情況恢復故障的:

方法返回成功,但事實並非如此。它應該是失敗的。請讓我知道這個問題是什麼問題。

回答

1

您觀察到的event流永遠不會返回失敗。見它的文檔:

/// A signal of all events generated from applications of the Action. 
/// 
/// In other words, this will send every `Event` from every signal generated 
/// by each SignalProducer returned from apply() except `ActionError.disabled`. 
public let events: Signal<Event<Output, Error>, NoError> 

觀察成功的價值觀,你想訂閱values,並使用observeValues

self.viewModel?.getListAction 
    .values 
    .take(during: lifetime) 
    .observeValues { [weak self] value in 
     // always successful 
    } 

如果你想看到的錯誤,你可以訂閱errors和使用observeValues

self.viewModel?.getListAction 
    .errors 
    .take(during: lifetime) 
    .observeValues { [weak self] error in 
     // error event 
    } 
相關問題