Skip to content

Instantly share code, notes, and snippets.

@ShinichiroFunatsu
Last active July 31, 2020 05:27
Show Gist options
  • Save ShinichiroFunatsu/165d0026760deef4a4d669a660dea6ec to your computer and use it in GitHub Desktop.
Save ShinichiroFunatsu/165d0026760deef4a4d669a660dea6ec to your computer and use it in GitHub Desktop.
LiveData Event Mediator Beta
interface EventMediator<T> {
interface Input<T> {
fun bind(input: LiveData<T>)
}
interface Output<T> {
val onAction: LiveData<T>
}
val input: Input<T>
val output: Output<T>
companion object {
fun <T> create() = object : EventMediator<T> {
override val output = object : Output<T> {
override val onAction: MediatorLiveData<T> = MediatorLiveData()
}
override val input = object : Input<T> {
override fun bind(input: LiveData<T>) {
output.onAction.addSource(input) {
output.onAction.value = it
}
}
}
}
}
}
@ShinichiroFunatsu
Copy link
Author

class FooListViewModel {
    private val eventMediator = FooListEventMediator()
    val listItemClick: EventMediator<FooListItem>
        get() = eventMediator.listItemClick
}
class FooListEventMediator {
    val listItemClick: EventMediator<FooListItem> = EventMediator.create()
}

@ShinichiroFunatsu
Copy link
Author

適当につくったけど、これでは単にMediatorLiveDataの方が良さそうに見える

@ShinichiroFunatsu
Copy link
Author

ShinichiroFunatsu commented Jul 31, 2020

This is better than custom something.

    val listItemClickEventInput = MediatorLiveData<FooListItem>()
    val listItemClickEventOutput: LiveData<FooListItem>
        get() = listItemClickEventInput

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment