Skip to content

Instantly share code, notes, and snippets.

@randallmitchell
Last active April 28, 2018 04:02
Show Gist options
  • Save randallmitchell/edcd85034e26449473bd7412c45f2e7f to your computer and use it in GitHub Desktop.
Save randallmitchell/edcd85034e26449473bd7412c45f2e7f to your computer and use it in GitHub Desktop.
Solving Android Inactive Lifecycle State Data Events in a Reactive Environment using Relays
package com.methodsignature.sample
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.jakewharton.rxrelay2.BehaviorRelay
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
data class Data(
val id: Long,
val text: String
)
class ViewDataInteractor {
fun connect(): Observable<Data> {
return Observable.just(Data(0, "text"))
}
}
class Presenter(private val dataObservable: Observable<Data>) {
private val disposables = CompositeDisposable()
fun onStart() {
val disposable = dataObservable.subscribe {
// update UI
}
disposables.add(disposable)
}
fun onStop() {
disposables.clear()
}
}
class Activity: AppCompatActivity() {
private lateinit var presenter: Presenter
private val interactor = ViewDataInteractor()
private val dataRelay = BehaviorRelay.create<Data>()
private val disposables = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val disposable = interactor.connect()
.subscribe {
dataRelay.accept(it)
}
disposables.add(disposable)
presenter = Presenter(dataRelay)
}
override fun onDestroy() {
super.onDestroy()
disposables.clear()
}
override fun onStart() {
super.onStart()
presenter.onStart()
}
override fun onStop() {
super.onStop()
presenter.onStop()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment