Editable synced sort order

2019-06-02 11:10发布

How could I implement Firestore so that users can sort items in an array and the sort order is synced? For example order items in a Todo list.

I can come up with 2 alternatives. But they don't feel like good ideas..

  1. Insert an item at a specified index. But I'm not sure how to or if you can do that with Firestore?

  2. Every time you add a new item or "move" an item map new sortKey-values to each item then update all items. I might be able to so this with .batch but it feels super inefficient?

There must be a better way!

1条回答
狗以群分
2楼-- · 2019-06-02 11:51

What I'd recommend is to have a position field in your document that you will set to a floating point value. Listen to the collection with the query ordered by position. Then:

  1. When putting an item at the end, give it a position of lastItem.position + 100
  2. When moving an item, set position to (prev.position + next.position) / 2.0
  3. When moving an item to the head of the line, firstItem.position / 2.0

This way you can continuously reorder items without having to do batched writes. Let's take a look at an example:

A: 100                   C:  50                    C:  50
B: 200                   A: 100 -> move below B    B: 200
C: 300 -> move to top    B: 200                    A: 300
D: 400                   D: 400                    D: 400
查看更多
登录 后发表回答