LoginSignup
1
4

More than 5 years have passed since last update.

EventBusの登録・解除をLifecycleで(少し)エレガントに書く

Last updated at Posted at 2018-08-04

EventBus + LifecycleObserver

アクティビティ等でEventBusを使用するにはregisterunregisterが必要なのですが、毎回onStart/onStopにコードを書くのがアレなので、Android Lifecycle Architectureを使用して、少しエレガントに書きます。

まずは、ライブラリが必要なので、build.gradleに以下を追記します。
(EventBusはもう追加してある前提です)

implementation "android.arch.lifecycle:extensions:1.1.1"

続いて、Observerを作成します。

EventBusLifecycleObserver.kt
class EventBusLifecycleObserver(private val owner: LifecycleOwner) : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun register() {
        EventBus.getDefault().register(owner)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun unregister() {
        EventBus.getDefault().unregister(owner)
    }
}

onStartでregisterして、onStopでunregisterするだけのオブザーバです。

これをMainActivityから使用する場合は、次のようにLifecycleOwnerをimplementsして、onCreate内でaddObserverしてあげます。

MainActivity.kt
class MainActivity : AppCompatActivity(), LifecycleOwner {
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(EventBusLifecycleObserver(this))
    }
    ...

これでMainActivityでイベントを@Subscribeすることができるようになります。

アクティビティ内に色んな処理が増えてくると、onXXXX系メソッドがすぐに汚れちゃうんですが、このようにLifecyleを使用すればスッキリします。もうこれなしでは生きていけません。

余談

どうせほとんどのアクティビティでEventBusを使用するんだという場合には、アクティビティの抽象クラスを作っておいて、オプションで使用する/しないを選択できるようにしてもいいかもしれません。

BaseActivity.kt
abstract class BaseActivity(private val useEventBus: Boolean = false)
    : AppCompatActivity(), LifecycleOwner {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (useEventBus) {
            lifecycle.addObserver(EventBusLifecycleObserver(this))
        }
    }
}

これで継承時にオプションを渡す感覚で使用するこができます。

MainActivity.kt
class MainActivity : BaseActivity(useEventBus = true) {

Kotlin、素敵過ぎます。

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4