Filter @ObservedResults dynamically

Using where: ( { some query } ) one can filter the @ObservedResults of an implicitly opened realm. I need to filter these results dynamically, so for example using some variable that is available only after the init of the view has run. How would I achieve this?

Example:

struct Example: View {
    @EnvironmentObject var state: AppState
    
    @ObservedResults(Task.self,
                     where: ( { $0.creatorId == state.userID! } )) var tasks

    var body: some View {
        Text("\(tasks.count)")
    }
}

would throw an error: “Cannot use instance member ‘state’ within property initializer; property initializers run before ‘self’ is available” which makes sense… but how would I use something in state to filter the data?

cc @Jason_Flax

You just have to filter those down below rather than in the initializer.

Try it like this:

struct Example: View {
    @EnvironmentObject var state: AppState
    
    @ObservedResults(Task.self) var tasks

    var body: some View {
      if let filteredTasks = tasks.where({ $0.creatorId == state.userID! }) {
        Text("\(filteredTasks.count)")
    }
}

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.