본문 바로가기

Study/Android

[Android] RxEventBus

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

 

Super simple event bus with RxJava and Kotlin

I wanted to implement a simple event bus with RxJava and Kotlin that did not require any if statements, switch statements, when statements…

medium.com