RxSwift驱动程序值

时间:2018-01-18 15:18:12

标签: swift cocoa-touch rx-swift

在我的应用程序中,我有一系列通知。通知可以读取和读取。

当用户点击未读通知时,我需要更改模型并在表格视图中重新加载数据。

在我的ViewModel中,我有输出流:

let notifications: Driver<[Notification]>

并且我有一个带有通知点击的输入流:

let touchSingleNotificationIntent = PublishSubject<Notification>()

当我做这样的事情时,我得到的错误就是让它不变,我不能改变它。

touchSingleNotificationIntent
        .filter { !$0.isRead }
        .do(onNext: { notification in
            notification.isRead = true // I need to change state of the model immediately after user iteration
        })
        .map { $0.notificationID }
        .flatMap(markNotificationAsRead) // http request which doesn't reply with current notification model status
        .subscribe()
        .disposed(by: bag)

你有什么想法让它变得可变吗?感谢。

2 个答案:

答案 0 :(得分:1)

Streams根本不可变(ObservableDriver和任何其他特征都是相同的。它们是&#34;只读&#34;,您随时间读取流中的值。

一般来说,概念Observables有一个&#34;值&#34;有点错误,因为Observables代表一段时间内的值,而不仅仅是一个值。

你想要做的是&#34;考虑到&#34;在构建驱动程序时PublishSubject

这样的事情会起作用:

notifications = Observable
    .combineLatest(touchedNotification, readNotification, otherEvent) { ($0, $1, $2) }
    .map { ... map the three values into whatever makes sense for you }
    .asDriver(onErrorJustReturn: ... fallback value ... }

同样,要记住的最重要的事实 - 你实际上并不改变流,你只需要将它们组合起来,转换它们等,以创建一个适合你需要的新流。

希望这能帮到你!

答案 1 :(得分:0)

onNext 的参数默认为 let 。您可以使用 var 定义一个新的,即“var newNotification = notification”,然后在修改后返回它。

相关问题