Giter Club home page Giter Club logo

Comments (10)

Succete avatar Succete commented on August 15, 2024 7
import Foundation
import RealmSwift
import RxSwift
import RxRealm
import RxDataSources
import RxOptional

class Goal: Object {
    dynamic var name = ""
}

struct GoalSection {
    var header: String
    var items: [GoalItem]
}

struct GoalItem {
    let goal: Goal
}

extension GoalSection: AnimatableSectionModelType {
    typealias Item = GoalItem
    var identity: String {
        return header
    }
    init(original: GoalSection, items: [GoalItem]) {
        self = original
        self.items = items
    }
}

extension GoalItem: IdentifiableType {
    typealias Identity = Goal
    var identity: Goal {
        return goal
    }
}

extension GoalItem: Equatable {}
func == (lhs: GoalItem, rhs: GoalItem) -> Bool {
    return lhs.goal == rhs.goal
}

enum GoalListCommand {
    case Set(List<Goal>)
    case Add(Goal)
    case Update(Goal, NSIndexPath)
    case Delete(NSIndexPath)
}

struct GoalSectionModel {
    let sections: [GoalSection]
    func executingCommand(command: GoalListCommand) -> GoalSectionModel {
        switch command {
        case let .Set(goals):
            let items = goals.map(GoalItem.init)
            let section = GoalSection(header: "goalList", items: items)
            return GoalSectionModel(sections: [section])
        case let .Add(goal):
            var sections = self.sections
            var section = sections.first!
            let item = GoalItem(goal: goal)
            section.items.append(item)
            sections[0] = section
            return GoalSectionModel(sections: sections)
        case let .Delete(indexPath):
            var sections = self.sections
            var section = sections.first!
            section.items.removeAtIndex(indexPath.row)
            sections[0] = section
            return GoalSectionModel(sections: sections)
        case let .Update(goal, indexPath):
            var sections = self.sections
            var section = sections.first!
            section.items[indexPath.row] = GoalItem(goal: goal)
            sections[0] = section
            return GoalSectionModel(sections: sections)
        }
    }
}

class GoalVM {

    let tablevm: Observable<[GoalSection]>

    init(goalList: List<Goal>) {
        let initialCommand = Observable.just(GoalListCommand.Set(goalList))

        let changeCommands = goalList
            .asObservableChangeset()
            .flatMap { (_, changeset) -> Observable<Observable<GoalListCommand>> in
                guard let changeset = changeset else { return Observable.empty() }
                let delete = changeset.deleted.first == nil ?
                    Observable.empty() :
                    Observable.just(changeset.deleted.first)
                        .filterNil()
                        .map { GoalListCommand.Delete(NSIndexPath(forRow: $0, inSection: 0)) }
                let insert = changeset.inserted.first == nil ?
                    Observable.empty() :
                    Observable.just(changeset.inserted.first)
                        .filterNil()
                        .map { _ in GoalListCommand.Add(goalList.last!) }
                let update = changeset.updated.first == nil ?
                    Observable.empty() :
                    Observable.just(changeset.updated.first)
                        .filterNil()
                        .map { GoalListCommand.Update(goalList[$0], NSIndexPath(forRow: $0, inSection: 0)) }
                return Observable.of(delete, insert, update)
            }
            .merge()

        let commands = Observable.of(initialCommand, changeCommands)
            .merge()

        tablevm = commands
            .scan(GoalSectionModel(sections: [])) { $0.executingCommand($1) }
            .map { $0.sections }
    }
}

// goalList is List<Goal> datas
let vm = GoalVM(goalList: goalList)
let dataSource = RxTableViewSectionedAnimatedDataSource<GoalSection>()

tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

dataSource.configureCell = { (ds, tv, ip, item) in
            let cell = tv.dequeueReusableCellWithIdentifier("cell", forIndexPath: ip)
            cell.textLabel?.text = item.goal.name
            return cell
        }

vm.tablevm
            .bindTo(tableView.rx_itemsWithDataSource(dreamTableData))
            .addDisposableTo(disposeBag)

It's just an example.

from rxdatasources.

icanzilb avatar icanzilb commented on August 15, 2024 7

Realm works completely differently that static persistence layers like SQLite and CoreData, which is based on it. That's why using RxDataSources with RxRealm is dangerous - the Realm objects are alive and will change as the data changes on disk, while RxDataSources assumes that the data is static and will not change on its own.

A RxRealmDataSources is in the works to make most of what Realm offers but it's still WIP. My best advice, for the time being, is to use the code in the RxRealm demo app - this is the fastest code with least overhead.

The big example in the comment above introduces much of unneeded complexity and achieves the same effect, plus introduces the possibility of a runtime crashes by using RxDataSources with RxRealm.

from rxdatasources.

whisper-bye avatar whisper-bye commented on August 15, 2024 1

@kzaher
@icanzilb
https://github.com/RxSwiftCommunity/RxRealm/blob/master/Example/RxRealm/ViewController.swift
In this case, it's bind directly to tableView, but I don't know how to bind to dataSource

from rxdatasources.

kzaher avatar kzaher commented on August 15, 2024

Hi @whisper-bye ,

take a look at Example app inside this repo. It contains those examples also.

from rxdatasources.

whisper-bye avatar whisper-bye commented on August 15, 2024

Hi @kzaher thx for your reply
I've seen it already, but I still don't understand how to bind dataSource with RxRealm...

from rxdatasources.

Succete avatar Succete commented on August 15, 2024
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Lap>>()
let laps = realm.objects(Lap).sorted("time", ascending: false).asObservableArray()
laps.flatMap { Observable.just([SectionModel(model: "test", items: $0)]) }
            .bindTo(tableView.rx_itemsWithDataSource(dataSource))
            .addDisposableTo(bag)

It's just a simple example.

from rxdatasources.

whisper-bye avatar whisper-bye commented on August 15, 2024

@Succete
oh! thx for your reply, It's exactly what I wanted!
I'm looking at it now.

from rxdatasources.

Succete avatar Succete commented on August 15, 2024

@whisper-bye you're welcome.

from rxdatasources.

LiuSky avatar LiuSky commented on August 15, 2024

@Succete Swift3.0 Is there a better way to deal with after RxRealm RxData and binding。thank you

from rxdatasources.

LiuSky avatar LiuSky commented on August 15, 2024

from rxdatasources.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.