Android/Kotlin

RxBus

lipnus 2019. 2. 15. 12:39
반응형


RxBus

액티비티, 서비스, 프레그먼트 서로간에 이벤트를 주고받을 수 있다.


https://android.jlelse.eu/rxbus-kotlin-listen-where-ever-you-want-e6fc0760a4a8



Gradle

implementation "io.reactivex.rxjava2:rxjava:2.0.1"



싱글톤

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)
}


이벤트 정의

class RxEvent {

data class EventAddPerson(
val personName: String
)
}


보내는곳

RxBus.publish(RxEvent.EventAddPerson("김메롱"))

이게 끝. 개간단



받는곳

class MainActivity : AppCompatActivity() {

private lateinit var personDisposable: Disposable

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)


personDisposable = RxBus.listen(RxEvent.EventAddPerson::class.java).subscribe {
Log.d("SSS", "서비스의 메시지: ${it.personName}")
}


}



override fun onDestroy() {
super.onDestroy()
if (!personDisposable.isDisposed) personDisposable.dispose()
}
}


반응형

'Android > Kotlin' 카테고리의 다른 글

클립보드 복사  (0) 2019.03.08
Dialog  (0) 2019.02.27
First-class citizen (1급객체)  (0) 2019.02.01
Higher-order-function(고차함수)  (0) 2019.02.01
const val과 그냥 val의 차이  (0) 2019.01.22