Last active
July 11, 2017 18:27
-
-
Save clackbib/9e79be5c2a54d8313d9022d87f95f856 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface PostRepository { | |
fun loadPost(id: String): Observable<Post> | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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