Created
June 19, 2019 10:18
-
-
Save vitoksmile/c2d2221cfd89497659553994ee9c8d48 to your computer and use it in GitHub Desktop.
LifecycleEventBus - simplifies the communication between components with LifecycleOwner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.LifecycleObserver | |
import androidx.lifecycle.LifecycleOwner | |
import androidx.lifecycle.OnLifecycleEvent | |
import java.util.WeakHashMap | |
/** | |
* LifecycleEventBus - simplifies the communication between components with LifecycleOwner | |
*/ | |
object LifecycleEventBus { | |
interface OnEventReceiveListener { | |
fun onEventReceived(event: Any) | |
} | |
private val subscribers = WeakHashMap<String, OnEventReceiveListener>() | |
/** | |
* Register new [subscriber] to event with the [name] | |
*/ | |
fun register(name: String, subscriber: OnEventReceiveListener) { | |
subscribers[name] = subscriber | |
} | |
/** | |
* Unregister subscriber from event with the [name] | |
*/ | |
fun unregister(name: String) { | |
subscribers.remove(name) | |
} | |
/** | |
* Send the [event] to subscriber | |
*/ | |
fun send(event: Any) { | |
// Find subscriber by event class name | |
val subscriber = subscribers[event::class.java.name] | |
// Notify the subscriber | |
subscriber?.onEventReceived(event) | |
} | |
} | |
class EventsSubscriber( | |
lifecycleOwner: LifecycleOwner, | |
eventClassName: String, | |
private val listener: LifecycleEventBus.OnEventReceiveListener | |
) : LifecycleObserver { | |
private val name: String = eventClassName | |
init { | |
lifecycleOwner.lifecycle.addObserver(this) | |
} | |
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) | |
fun subscribe() { | |
LifecycleEventBus.register(name, listener) | |
} | |
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) | |
fun unsubscribe() { | |
LifecycleEventBus.unregister(name) | |
} | |
} | |
/** | |
* Create subscription to [T]-event in the [lifecycleOwner] | |
*/ | |
inline fun <reified T> listenEvent( | |
lifecycleOwner: LifecycleOwner, | |
crossinline listener: (event: T) -> Unit | |
) = EventsSubscriber( | |
lifecycleOwner, | |
T::class.java.name, | |
object : LifecycleEventBus.OnEventReceiveListener { | |
override fun onEventReceived(event: Any) { | |
listener(event as T) | |
} | |
}) | |
/** | |
* Send new [event] | |
*/ | |
fun sendEvent(event: Any) = LifecycleEventBus.send(event) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment