2016-08-09 43 views
0

如何使用ReactiveX按顺序执行异步调用? 即,在第一个完成后执行第二个呼叫。如何使用ReactiveX按顺序执行异步

更具体地说,我在iOS中使用RxSwift,我想链接在一起的异步是UIView动画(而不是调用第一个的completion块内的第二个动画)。

我知道我有其他选项,例如Easy Animation,但我想利用Rx,因为我已经在使用它来处理流。

而且,一个解决办法是(3个链式动画):

_ = UIView.animate(duration: 0.2, animations: { 
     sender.transform = CGAffineTransformMakeScale(1.8, 1.8) 
    }) 
    .flatMap({ _ in 
     return UIView.animate(duration: 0.2, animations: { 
      sender.transform = CGAffineTransformMakeScale(0.8, 0.8) 
     }) 
    }) 
    .flatMap({ _ in 
     return UIView.animate(duration: 0.2, animations: { 
      sender.transform = CGAffineTransformIdentity 
     }) 
    }) 
    .subscribeNext({ _ in }) 

但是我正在寻找的东西更优雅,其中RX这样做的正确方法。

+0

怎么了你的代码示例?你的意思是它是伪代码吗?你在'Void'上调用'flatMap',而不是'SequenceType'或'Observable'。另外,animateWithDuration:动画:',而不是'animate:动画:'。我不确定你打算加入该代码的意图。 – solidcell

+0

我创建了'animate:...'方法来返回一个observable,所以不,不是伪代码 –

回答

2

我不使用Rx想使它更清洁,但这里是你如何能做到这一点:

let animation1 = Observable<Void>.create { observer in 
    UIView.animateWithDuration(0.2, 
     animations: { 
      // do your animations 
     }, completion: { _ in 
      observer.onCompleted() 
     }) 
    return NopDisposable.instance 
} 

let animation2 = Observable<Void>.create { observer in 
    UIView.animateWithDuration(0.2, 
     animations: { 
      // do your animations 
     }, completion: { _ in 
      observer.onCompleted() 
     }) 
    return NopDisposable.instance 
} 

Observable.of(animation1, animation2) 
    .concat() 
    .subscribe() 
    .addDisposableTo(disposeBag) 

这也将是清洁的,如果你创建一个函数来构建Observable<Void>给你的。

func animation(duration: NSTimeInterval, animations:() -> Void) -> Observable<Void> { 
    return Observable<Void>.create { observer in 
     UIView.animateWithDuration(duration, 
      animations: animations, 
      completion: { _ in 
       observer.onCompleted() 
      }) 
     return NopDisposable.instance 
    } 

我猜正侧的使用Rx,而不是仅仅animateWithDuration:animations:链,就是你不必窝在完成块的动画。这样,你可以自己定义它们,然后按照你想要的方式组合它们。

作为RxSwift的替代方案,请查看PromiseKit。对于您的动画回调需求来说,RxSwift有点矫枉过正。 This blog post尤其是相关的。

+0

不会'Observable.of(animation1,animation2).concat()'并行运行它们? –

+0

,你会使用除'Rx'之外的其他东西吗?这正是我的问题,我不想嵌套回调。 –

+0

另外,为什么我需要'.addDisposableTo(disposeBag)'?观察员完成后不应该自行离开? –

1

或许对于@Rodrigo Ruiz来说太迟了,但我相信这可能会帮助碰巧遇到这篇文章的其他开发者(就像我一样)。

RxAnimated是免费的在GitHub上:https://github.com/RxSwiftCommunity/RxAnimated

您可以使用此blog post

一个小的披露开始 - 我没有连接到该项目或交以任何方式 - 我只是发现它同时为我的动画寻找反应性解决方案:)