Skip to content

Instantly share code, notes, and snippets.

@clackbib
Last active July 11, 2017 18:27
Show Gist options
  • Save clackbib/9e79be5c2a54d8313d9022d87f95f856 to your computer and use it in GitHub Desktop.
Save clackbib/9e79be5c2a54d8313d9022d87f95f856 to your computer and use it in GitHub Desktop.
class PostFragment : Fragment() {
private lateinit var bin: CompositeDisposable
private lateinit var vm: PostViewModel
private lateinit var id: String
private lateinit var title: TextView
private lateinit var body: TextView
private lateinit var refreshButton: Button
// Kotlin's extension methods can provide syntactic sugar
fun Disposable.into(bin: CompositeDisposable) {
bin.add(this)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bin = CompositeDisposable()
vm.content(id)
.observeOn(AndroidSchedulers.mainThread())
.subscribe { data ->
title.text = data.title
body.text = data.body
}.into(bin)
vm.refreshClicks(RxView.clicks(refreshButton))
.subscribe()
.into(bin)
}
override fun onDestroyView() {
super.onDestroyView()
bin.dispose()
}
}
interface PostRepository {
fun loadPost(id: String): Observable<Post>
}
class PostViewModel {
private lateinit var refreshRequests: PublishSubject<Boolean>
private lateinit var repo: PostRepository
fun content(id: String): Observable<PostViewState> {
return Observable.just(true)
.mergeWith(refreshRequests)// Merge with subject to trigger a refresh.
.observeOn(Schedulers.io())
.switchMap { repo.loadPost(id) }
.map { post -> PostViewState(post.title, post.content) }
}
// You could substitute this for any input type. Clicks/Pulls to refresh, Event a timed interval.
fun refreshClicks(requests: Observable<out Any>): Observable<out Any> {
return requests.doOnNext { refreshRequests.onNext(true) }
}
}
data class PostViewState(val title: String,
val body: String)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment