簡體   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