Nozbe / WatermelonDB

🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️
https://watermelondb.dev
MIT License
10.58k stars 596 forks source link

How to get relationships from an observable array of Model #1642

Open AgusMaris opened 1 year ago

AgusMaris commented 1 year ago

Hi people, I have the following schema:

image

And I would like to get in my component all the Sensors for a specific user (I know this may not be a good approach but maybe each user will have no more than 20 sensors, so it's ok to have them all in memory) with its data (measurements and status for each measurement) in one step, I have the following code for my observable:

  observeSensorForUser(userId: string) {
    const sensorsQuery = SensorRepository.query(
      Q.where(Columns.Sensors.user_id, userId),
    );

    return sensorsQuery.observe().pipe(map(sensors => sensors.map(mapSensor)));
  }

That I use inside the screen that I want to show everything using this enhancer:

const enhance = withObservables([], () => {
  return {
    sensors: SensorService.observeSensorForUser('USER_ID'),
  };
});

I know that I can use multiple calls to withObservable HOC by doing small components to show specific data, for this app, it may bes better to do it that way. But I have another app in mind that uses a bunch of logic and domain rules I would like to get everything first in one step instead of some pieces of data in various components

finik-htec commented 1 year ago

Hi @AgusMaris, not sure if this will help you, but we had similar issue, so some of ways to solve these kind of issues are:

  1. You could use switchMap from rxjs which can be async, so you could fetch rest of data regarding each sensor inside switchMap function, and merge it to one object
  2. You could fetch all data separately ( sensors, measurements, etc...) and then use some of rxjs methods to combine multiple observables, like combineLatest, and then inside of it merge data together to one array
  3. Write down sql query and fetch raw data