[英]RxSwift, how to use NotificationCenter more gently?
Got a IAP purchased notification, then I request the transaction from my server.收到 IAP 购买通知,然后我从我的服务器请求交易。
To download a song and play, if transaction OK.下载歌曲并播放,如果交易OK。
I use RxSwift, The following code works, I want to improve it.我使用 RxSwift,以下代码有效,我想改进它。
NotificationCenter.default.rx.notification( .purchase )
.takeUntil(self.rx.deallocated)
.map { (noti) -> String in
return "Not care"
// I want to optimize this step
}.concat(self.transactionRequest())
.flatMap{ self.downloadSong($0) }.subscribe(onNext: { downloaded in
if downloaded{
self.playMusic()
}
})
.disposed(by: rx.disposeBag)
func transactionRequest() -> Observable<String> { // ... }
func downloadSong(_ src: String) -> Observable<Bool> { // ... }
I can not use like this我不能这样使用
NotificationCenter.default.rx.notification( .purchase )
.takeUntil(self.rx.deallocated)
.concat(self.transactionRequest())
because因为
Instance method 'concat' requires the types 'Notification' and 'String' be equivalent
实例方法 'concat' 要求类型 'Notification' 和 'String' 是等价的
So I add a boilerplate map
所以我添加了一个样板
map
Any more proper operator, or custom operator?还有更合适的运算符或自定义运算符吗?
The return type of the Observable that is feeding concat
and the one that is passed to concat
must be the same.提供
concat
concat
返回类型必须相同。 I suggest you use flatMap instead.我建议您改用 flatMap 。 Also, you are capturing
self
all over the place which means memory issues.此外,您正在到处捕捉
self
,这意味着 memory 问题。
Here's how I would do it:这是我的做法:
NotificationCenter.default.rx.notification(.purchase)
.flatMapLatest { [unowned self] _ in self.transactionRequest() }
.flatMapLatest { [unowned self] in self.downloadSong($0) }
.subscribe(onNext: { [unowned self] downloaded in
if downloaded {
self.playMusic()
}
})
.disposed(by: rx.disposeBag)
If you didn't put all your functions inside the class, you could get rid of the self.
如果你没有把你所有的功能都放在 class 里面,你可以摆脱
self.
and not have to worry about capturing self.并且不必担心捕获自我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.