Last active
December 10, 2015 07:02
-
-
Save kubode/56fd383f8c1dcf6f20ff to your computer and use it in GitHub Desktop.
Rxを使ったEventBusの実装
This file contains hidden or 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 rx.Scheduler | |
import rx.Subscription | |
import rx.subjects.PublishSubject | |
import kotlin.reflect.KClass | |
/** | |
* [rx]を使ったイベントバス | |
*/ | |
class EventBus { | |
private val publishSubject: PublishSubject<Event> = PublishSubject.create() | |
/** | |
* イベントを投げる。ハンドリングされなかった場合は新たに[DeadEvent]を投げる。 | |
*/ | |
fun post(event: Event) { | |
publishSubject.onNext(event) | |
if (event.handledCount == 0) { | |
publishSubject.onNext(DeadEvent(event)) | |
} | |
} | |
/** | |
* イベントのハンドリング登録。 | |
* 必ず戻り値に対して[Subscription.unsubscribe]をすること。 | |
*/ | |
fun <E : Event> subscribe(clazz: KClass<E>, onNext: (E) -> Unit, observeOn: Scheduler? = null): Subscription { | |
return publishSubject | |
.ofType(clazz.java) | |
.doOnNext { it.handledCount++ } | |
.run { observeOn?.let { observeOn(it) } ?: this } | |
.subscribe(onNext) | |
} | |
} | |
/** | |
* イベントの抽象クラス | |
*/ | |
abstract class Event { | |
internal var handledCount: Int = 0 | |
} | |
/** | |
* [EventBus.post]されたイベントがハンドリングされなかった場合、このイベントでラップして再度投げる | |
*/ | |
class DeadEvent(val event: Event) : Event() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment