Skip to content

Instantly share code, notes, and snippets.

@cloudbank
Forked from pbochenski/ViewModel.kt
Created January 9, 2018 09:03
Show Gist options
  • Save cloudbank/1a68649c110bde6dc69441dd87a61dab to your computer and use it in GitHub Desktop.
Save cloudbank/1a68649c110bde6dc69441dd87a61dab to your computer and use it in GitHub Desktop.
LiveData meets RxJava
compile "android.arch.lifecycle:reactivestreams:$archVersion"
class PostRepo(private val api: Api) {
private sealed class Command {
class Reset(val size: Int) : Command()
class LoadMore(val position: Int, val size: Int) : Command()
}
private var itemIds = emptyList<Long>()
private val commands = MutableLiveData<Command>()
val posts: LiveData<List<Item>> = commands.switchMap {
...
}
fun load(size: Int) {
itemIds = emptyList()
commands.value = Command.Reset(size)
}
fun loadMore(size: Int) {
commands.value = Command.LoadMore(posts.value?.size ?: 0, size)
}
}
fun <T, R> LiveData<T>.switchMap(f: (T) -> LiveData<R>): LiveData<R> = Transformations.switchMap(this, f)
val posts: LiveData<List<Item>> = commands.switchMap {
val command = it
LiveDataReactiveStreams.fromPublisher<List<Item>> {
when (command) {
is Command.Reset -> {
getFirst(command.size)
}
is PostRepo.Command.LoadMore -> {
getMore(command.position, command.size)
}
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.toFlowable()
.subscribe(it)
}
}
class MainViewModel(app: Application) : AndroidViewModel(app) {
private val postRepo = getApplication<App>().postRepo
private val LOAD_ITEM_COUNT = 15
fun getPosts(): LiveData<List<Post>> {
return postRepo.posts.map {
it.map { Post(it.id, it.title, it.url) }
}
}
fun refresh() {
postRepo.load(LOAD_ITEM_COUNT)
}
fun loadMore() {
postRepo.loadMore(LOAD_ITEM_COUNT)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment