繁体   English   中英

突变RxSwift驱动程序值

[英]Mutating of RxSwift Driver value

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

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

在我的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)

您有任何想法如何使其可变吗? 谢谢。

流根本不是可变的( ObservableDriver和其他任何特征都是相同的)。 它们是“只读”的,随着时间的流逝,您将读取值。

通常,可观察对象具有“值”的概念有点错误,因为可观察对象表示随时间推移的一个值,而不仅仅是单个值。

您要做的是在构建驱动程序时“考虑” 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 ... }

同样,要记住的最重要的事实-您实际上并未对流进行突变 ,而只是将它们组合,转换等,以创建适合您需求的新流。

希望这对您有所帮助!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM