Convert Realm objects to non-third-party objects in a lazy way: Results<Item> to [Item]

51 views Asked by At

I'm trying to map Realm Persisted Objects to another Type for separation of concerns.

I have something like a protocol repository retrieving an array of items: [Item]

I've one implementation of this repository using Realm, so I'm trying to convert a Results<PersistedItem> to [Item]

Results<PersistedItem> is lazy by default when you use it directly in a view but then your whole app is dependent on Realm as you need to import Realm in every views.

I've tried this LazyList implementation but every items are returning at once:

func items() -> LazyList<Item> {
    let dbItems = realm.objects(PersistedItem.self) // return List<PersistedItem>
    
    return LazyList(count: dbItems.count, useCache: true) { index in
        print(index) // this is printing every index
        return Item(persistedItem: dbItems[index])
    }
}

Then I simply access this LazyList in iOS SwiftUI List. This is working with default Realm collection but not with this LazyList implementation.

struct TestLazyView: View {
    
    // Working
    //let items: Results<PersistedItems>
    
    // Not Working as it's load every items at init
    let items: LazyList<Items>
    
    var body: some View {
        List(items) { item in
            Text(item.id)
        }
    }
}

What would be the approach to convert these items on demand? Thanks!

0

There are 0 answers