RxDataSources icon indicating copy to clipboard operation
RxDataSources copied to clipboard

CellConfiguration function gets called twice after the model is mutated in Realm

Open pajervoj03 opened this issue 6 years ago • 0 comments

Hi guys, first let me say that I really appreciate what you do. I love using RxDataSources!

I am working on an application that uses collection view to display educational courses. To simplify things up, the model of the course looks like this:

struct CourseModel {
    let id: String
    let fullName: String
    var bookmarked: Bool
    var completed: Bool
    var completedDate: Date?
}

And the section model for RxDataSources looks like this:

import RxDataSources

struct CourseSectionModel: AnimatableSectionModelType {
    typealias Item = CourseModel

    var items: [Item]
    var header: String

    init(items: [Item], header: String) {
        self.items = items
        self.header = header
    }

    init(original: CourseSectionModel, items: [Item]) {
        self = original
        self.items = items
    }
}

extension CourseSectionModel: IdentifiableType {
    typealias Identity = String

    var identity: String { return header }
}

extension CourseModel: IdentifiableType {
    typealias Identity = String

    var identity: String { return id }
}

extension CourseModel: Equatable {

    static func == (lhs: CourseModel, rhs: CourseModel) -> Bool {
        return lhs.id == rhs.id
            && lhs.bookmarked == rhs.bookmarked
            && lhs.completedDate == rhs.completedDate
    }
}

The courses are downloaded from API and saved to Realm. Afterwards, from the collection view, they are fetched from Realm, mapped via CourseEntity protocol to CourseModel and bound to collection view data source.

As you can see, the courses can be bookmarked or completed (indicated by the "Completed" badge over the course).

If the course is completed (=> completed badge is visible), when the data are bound to the collection view (the completion status is received from the API) and user clicks on the bookmark icon, everything works just fine. The bookmark icon nicely animates due to the Equatable difference in bookmarked property, cellConfiguration function gets called once.

However, if the course is not completed, when the data are bound to the collection view and user completes it in the app (=> the Realm db entity is updated and the "Completed" badge is shown), then, when user clicks on the bookmark icon, the cellConfiguration function gets called twice - once with the original model (completed = false) and once with the newly updated model (completed = true). Since the section model is AnimatedSectionModel, the "Completed" badge fades out and then fades in again.

If you want, I can post more source code, but everything is quite straight forward:

getDataFromDB() -> mapToModel() -> mapToSectionModel() -> bindToDataSource()

Thanks in advance for any help!

pajervoj03 avatar Nov 20 '19 17:11 pajervoj03