Skip to content

Instantly share code, notes, and snippets.

@mkorakin
Last active January 26, 2020 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkorakin/557dea509f757a3f3f9c5fcc8f720e78 to your computer and use it in GitHub Desktop.
Save mkorakin/557dea509f757a3f3f9c5fcc8f720e78 to your computer and use it in GitHub Desktop.
RxJava .autoConnect() example
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.jakewharton.rxbinding3.view.clicks
import com.jakewharton.rxrelay2.PublishRelay
import com.mkorakin.clicker.R
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observables.ConnectableObservable
import kotlinx.android.synthetic.main.activity_clicker.*
/**
* An example for using a [ConnectableObservable] to host a stream in a [ViewModel].
*/
class MyViewModel : ViewModel() {
private val viewModelDisposables = CompositeDisposable()
val userInput = PublishRelay.create<Input>()
val viewsState: Observable<ViewState> =
// A stream of user input
userInput
// Transformed to a stream of view states
.toViewState()
// Last state emitted is replayed to new subscribers
.replay(1)
// An upstream connection is made on the first subscription
// and shared with all future subscribers.
.autoConnect(1) { upstreamConnection ->
// Upstream disposable kept for later disposal.
viewModelDisposables.add(upstreamConnection)
}
override fun onCleared() {
viewModelDisposables.dispose()
super.onCleared()
}
/**
* Transform a stream of user events to a stream of updated view states.
*/
private fun Observable<Input>.toViewState(): Observable<ViewState> =
scan(ViewState(0)) { state, _ -> state.copy(clicksCount = state.clicksCount + 1) }
}
class AutoConnectExampleActivity : AppCompatActivity() {
private val activityDisposables = CompositeDisposable()
private val viewModel: MyViewModel by lazy {
ViewModelProviders.of(this).get(MyViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_clicker)
button
.clicks()
.map { Input }
.subscribe(viewModel.userInput::accept)
.let(activityDisposables::add)
viewModel
.viewsState
.observeOn(AndroidSchedulers.mainThread())
.subscribe(::render)
.let(activityDisposables::add)
}
private fun render(viewState: ViewState) {
button.text = viewState.clicksCount.toString()
}
override fun onDestroy() {
activityDisposables.dispose()
super.onDestroy()
}
}
object Input
data class ViewState(val clicksCount: Int)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment