implementation "io.reactivex.rxjava2:rxjava:2.2.19" 또는 최신 버전
RxBus.kt
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
// Use object so we have a singleton instance
object RxBus {
private val publisher = PublishSubject.create<Any>()
fun publish(event: Any) {
publisher.onNext(event)
}
// Listen should return an Observable and not the publisher
// Using ofType we filter only events that match that class type
fun <T> listen(eventType: Class<T>): Observable<T> = publisher.ofType(eventType)
}
RxBusDataClass.kt
// Custom MessageEvent class
data class MessageEvent(val action: Int,
val message: String)
// Listen for MessageEvents only
RxBus.listen(MessageEvent::class.java).subscribe({
println("Im a Message event ${it.action} ${it.message}")
})
// Listen for String events only
RxBus.listen(String::class.java).subscribe({
println("Im a String event $it")
})
// Listen for Int events only
RxBus.listen(Int::class.java).subscribe({
println("Im an Int event $it")
})
// Publish events
RxBus.publish(MessageEvent(1, "Hello, World"))
RxBus.publish("Testing")
RxBus.publish(123)
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val mDisposables = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
mDisposables.addAll(
RxBus.listen(Message::class.java).subscribe {
viewModel.onChatReceivedData(it.id, it.senderId, it.chatRoomId)
}
)
}
override fun onDestroy() {
super.onDestroy()
mDisposables.dispose()
}
}
참고 : https://medium.com/android-news/super-simple-event-bus-with-rxjava-and-kotlin-f1f969b21003
'Study > Android' 카테고리의 다른 글
[Mac] source ~/.bash_profile 명령어 적용 이슈 (0) | 2022.10.25 |
---|---|
앨범에서 사진/동영상/사진,동영상 모두 가져오기 (0) | 2022.09.20 |
Download Manager로 파일 다운 받는 방법 (0) | 2022.06.08 |
[Android/Kotlin] Live Template 예제 (0) | 2022.05.16 |
[Android/Kotlin] 커스텀 달력 만들기 (0) | 2022.04.12 |