reduxkotlin / redux-kotlin

Redux implementation for Kotlin (supports multiplatform JVM, native, JS, WASM)
https://reduxkotlin.org
MIT License
426 stars 32 forks source link

Unsubscribe StoreSubscription #11

Closed Pyeroh closed 5 years ago

Pyeroh commented 5 years ago

Currently, when subscribing to the store, a StoreSubscription is returned, but it's just an alias to () -> Unit. Subscriptions should be stored so they could be unsubscribed, otherwise it could lead to memory leaks.

erchenger commented 5 years ago

I could be wrong but from the little bit of reading I have done, I see that the subscribe() method returns a function that if you run will execute this code. I think this is handling exactly what you are looking for.

  return {
            if (!isSubscribed) {
                Unit
            }

            if (isDispatching) {
                throw Exception(
                        """You may not unsubscribe from a store listener while the reducer is executing.
                                'See https://redux.js.org/api-reference/store#subscribe(listener) for more details."""
                )
            }

            isSubscribed = false

            ensureCanMutateNextListeners()
            val index = nextListeners.indexOf(listener)
            nextListeners.removeAt(index)
        }
patjackson52 commented 5 years ago

Yes, @erchenger is correct. The function that is returned does the unsubscribed.

    val unsubscribe = store.subscribe { render(store.state) }

    unsubscribe()    // this unsubscribes and removes the reference

Naming of StoreSubscription is not really clear that this is an unsubscribe function. May consider changing the name.