pubkey / rxdb

A fast, local first, reactive Database for JavaScript Applications https://rxdb.info/
https://rxdb.info/
Apache License 2.0
21.37k stars 1.04k forks source link

collection.remove$ does not seem to be an observable? #6090

Closed MrChadMWood closed 3 months ago

MrChadMWood commented 3 months ago

I am working with data that is partitioned on the backend, and the client RxDB instance will only ever have data from one partition at a time. Different partitions are accessed via different directories in the HTTP Replication URL, so I'll have a process similar to this each time the client needs to switch partitions:

However, I'm noticing that nothing is logged when I use window.collection.remove() from the browser console. Am I misunderstanding how the observable works?

Am I misinterpreting the purpose of collection.remove$?

pubkey commented 3 months ago

collection.remove$ only emits document deletes, not when the collection is removed. You can use onRemove to detect that: https://rxdb.info/rx-collection.html#ondestroy--onremove

MrChadMWood commented 3 months ago

I see, that is my mistake. Thank you for linking the relevant documents.

MrChadMWood commented 3 months ago

@pubkey

I believe I'm following the documentation example here: await myCollection.onRemove(() => console.log('I am removed'));

I'm getting an error though: " Uncaught (in promise) TypeError: collection.onRemove is not a function "

After some debugging, it looks like my collection.onRemove is an array. Any idea what would be wrong here?

08:47:15.522 >>> window.collections.task.onRemove
    Array []
    length: 0
    <prototype>: Array []

Here's my implementation:

export async function createDatabase() {
    const db = await createRxDatabase({
        name: RxDB_DATABASE_NAME,
        storage: getRxStorageDexie(),
        multiInstance: true,
        eventReduce: true,
    });

    const collections = await db.addCollections({
        task: { schema: taskSchema },
        ...
    });

    window['collections'] = collections;

    Object.entries(collections).forEach(([name, collection]) => {
        collection.onRemove(() => console.log('Collection removed!'));
    });

    ...
MrChadMWood commented 3 months ago

Found the answer. RxDB seems to accept functions within the array and calls them.

08:58:55.649 >>> window.collections.task.onRemove.push(() => console.log('I have been removed!'))
    1

08:59:15.481 >>> window.collections.task.remove()
    Promise { <state>: "pending" }

08:59:15.494 I have been removed!