groue / GRDBCombine

GRDB ❤️ Combine
MIT License
223 stars 16 forks source link

Question about sample code #17

Closed skrew closed 4 years ago

skrew commented 4 years ago

Hi Gwendal,

I'm playing with GRDBCombine, but i have one question:

In the sample code, in HallOfFameViewModel, you have hardcoded the var maxPlayerCount:

@DatabasePublished(Current.players().hallOfFamePublisher(maxPlayerCount: 10))

How i can make this var dynamic so i can use it like HallOfFameViewModel(maxPlayerCount: 50) ?

When i try to make it dynamic, i got an error (which is normal):

Cannot use instance member 'maxPlayerCount' within property initializer; property initializers run before 'self' is available

groue commented 4 years ago

Hello @skrew,

Excellent question :-)

The only solution I'm aware of is to perform explicit instantiation of the property wrapper, as below:

class HallOfFameViewModel {
    @DatabasePublished
    var hallOfFame: Result<Players.HallOfFame, Error>

    init(maxPlayerCount: Int) {
        let publisher = Current.players().hallOfFamePublisher(maxPlayerCount: maxPlayerCount)
        _hallOfFame = DatabasePublished(publisher)
    }
}
groue commented 4 years ago

If maxPlayerCount has to be provided later, then there is no solution yet and you'd better use raw publishers instead of DatabasePublished.

Generally speaking, I have never tried to feed @DatabasePublished from the SwiftUI environment. @FetchRequest support this, but I have barely scratched the surface in this SO question: https://stackoverflow.com/questions/57668997

skrew commented 4 years ago

Yep it's works, thanks !

I'm still not sure to use SwiftUI for my new app (tvOS) because i wanted to reuse a lot of code from iOS version and, as i can see, It won't always be possible... It's maybe too early !

groue commented 4 years ago

Cool! You know, @DatabasePublished is pretty much in flux, and is the most experimental part of the lib. We'll have to really live with Combine and SwitfUI before we know what we need.