Loren
Loren

Reputation: 892

Firestore database to accommodate multiple users independently arranging items

I need some help designing the Firestore database for my app. The app has three requirements:

  1. Display documents in a recycler view;
  2. The user to rearrange document items via drag and drop; and
  3. Multiple users to access the documents and independently rearrange their items.

The first requirement is straight forward using a Firestore query.

The second requirement I’m planning to have a “position” field in the documents so the query can be “ordered by” the “position” field.

It’s the third requirement where I have difficulties. My first thought is to is to have multiple “position” fields associated with each user and order the query by the “user’s position” field. However, since Firestore requires an index for each query this approach does not work.

Any suggestions as to how best to design my Firestore database to accomplish the app’s three requirements would be appreciated.

Upvotes: 1

Views: 660

Answers (2)

Loren
Loren

Reputation: 892

For anyone else that is interested, below describes my changes:

  1. Excluded the “position” field from the Firestore item document. So, now when item documents are retrieved from Firestore they contain no position information. And they are downloaded in no particular order.
  2. I’ve created a new Firestore “state” document that has a “positions” field that is a map with its key as the item’s uid and a position Int as its value. (I’ve also included an Int field that holds the recycler view’s firstVisiblePosition and another that holds its offsetTop so the recycler view can be restored to its last position.)
  3. After the initial loading of item documents, the position values are applied to each item document. And the item documents are sorted by their position.
  4. I handle ADDED, MODIFIED, and REMOVED document change events in my recycler view’s adapter. The change events “oldIndex” and “newIndex” values are not used.
  5. Last, I save the “state” document under a user’s subCollection in the onStop lifecycle call back.

Hope this helps.

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317392

You could store each user's ordering in a per-user document or collection (organized separately from the data itself). Simply map each document id to that user's chosen position for it. This means you would also need a separate query to get that ordering, but you wouldn't need a new index at all.

Upvotes: 1

Related Questions