import $$observable from 'symbol-observable'

function observerPlugin(router) {
    let listeners = []

    function unsubscribe(listener) {
        if (listener) {
            listeners = listeners.filter(l => l !== listener)
        }
    }

    function subscribe(listener) {
        const finalListener =
            typeof listener === 'object' ? listener.next : listener

        listeners = listeners.concat(finalListener)

        return () => unsubscribe(finalListener)
    }

    function observable() {
        return {
            subscribe(observer) {
                if (typeof observer !== 'object' || observer === null) {
                    throw new TypeError(
                        'Expected the observer to be an object.'
                    )
                }

                function listener() {
                    if (observer.next) {
                        observer.next(router.getState())
                    }
                }

                listener()
                const unsubscribe = subscribe(listener)
                return { unsubscribe }
            },

            [$$observable]() {
                return this
            }
        }
    }

    router.subscribe = subscribe
    router[$$observable] = observable

    return {
        onTransitionSuccess: (toState, fromState) => {
            listeners.forEach(listener =>
                listener({
                    route: toState,
                    previousRoute: fromState
                })
            )
        }
    }
}

observerPlugin.pluginName = 'OBSERVABLE_PLUGIN'

export default function withObservablePlugin(router) {
    router.usePlugin(observerPlugin)
}

@@ -346,24 +346,71 @@
 ect'
- ? listener.next
+%0A                ? listener.next.bind(listener)%0A               
  : l
@@ -827,213 +827,8 @@
    %7D
-%0A%0A                function listener() %7B%0A                    if (observer.next) %7B%0A                        observer.next(router.getState())%0A                    %7D%0A                %7D%0A%0A                listener()
 %0A   
@@ -870,26 +870,27 @@
 bscribe(
-listen
+observ
 er)%0A
+%0A
         

improve observable interoperability