Newer
Older
MonCalc / app / src / main / kotlin / jackall / moncalc / utils / RxBus.kt
package jackall.moncalc.utils

import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.subjects.PublishSubject

/**
 * Created by matsumoto_k on 2017/11/05.
 */
object RxBus {

    private val subscriptionsMap: HashMap<Any, CompositeDisposable> by lazy {
        HashMap<Any, CompositeDisposable>()
    }

    val bus = (PublishSubject.create<Any>()).toSerialized()

    fun send(event: Any) {
        bus.onNext(event)
    }

    inline fun <reified eventType : Any> observe(): Observable<eventType> {
        return bus.ofType(eventType::class.java)
    }

    fun unregister(subscriber: Any) {
        val compositeSubscription = subscriptionsMap[subscriber]
        if (compositeSubscription == null) {
        } else {
            compositeSubscription.clear()
            subscriptionsMap.remove(subscriber)
        }
    }

    internal fun register(subscriber: Any, subscription: Disposable) {
        var compositeDisposable = subscriptionsMap[subscriber]
        if (compositeDisposable == null) {
            compositeDisposable = CompositeDisposable()
        }
        compositeDisposable.add(subscription)
        subscriptionsMap[subscriber] = compositeDisposable
    }
}

fun Disposable.registerInBus(subscriber: Any) {
    RxBus.register(subscriber, this)
}