2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Android】SharedFlowを使ってEventBusを作る

Posted at

前置き

いいね処理、お気に入り処理などの、画面間をまたいだイベント送信を行いたい場合、これまではEventBusottoを使っていた方が多いと思います。

ですが、SharedFlowを使えばライブラリを使わずとも自前で簡単に実装できるので、備忘録がてらサンプルを書いておきます。

実はSharedFlowの公式ページにもサンプルが書いてあります。
今回はそれをちょっとだけ弄っただけです:pray:

Sample

CoroutineEventStore.kt
class CoroutineEventStore {
    companion object {
        private var instance: CoroutineEventStore = CoroutineEventStore()
        fun getInstance() : CoroutineEventStore {
            return instance
        }
    }

    // Eventはこれを継承すること
    interface CoroutineEvent

    private val _events = MutableSharedFlow<CoroutineEvent>()
    val events = _events.asSharedFlow()

    suspend fun post(event: CoroutineEvent) {
        _events.emit(event)
    }
}

data class HogeEvent(val data: **): CoroutineEventStore.CoroutineEvent

使い方

送信

CoroutineEventStore.getInstance().post(hogeEvent)

受信

**Scope.launch {
  CoroutineEventStore.getInstance().events
    .mapNotNull { if (it is HogeEvent) it else null }
    .collect {
      // 受信時の処理を書く
    }
}

特に受信処理は各EventクラスごとにUseCaseなどで分けてあげると使いやすいと思います。
とっても簡単にEventBusが作れるのでありがたいですね:sunny:

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?