Skip to content

Instantly share code, notes, and snippets.

@AdamMc331
Created March 14, 2018 19:11
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 AdamMc331/60e08efa73b2dc874d0d072ee62a9076 to your computer and use it in GitHub Desktop.
Save AdamMc331/60e08efa73b2dc874d0d072ee62a9076 to your computer and use it in GitHub Desktop.
Notice how each function subscribes to an observable, sets the state based on the response, and otherwise logs an error? Is there a way to somehow combine these three methods into one?
private fun fetchAllFacebookAlbums() {
val subscription = socialPhotosViewModel.getAllFacebookAlbums()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
state = it
},
{
Timber.e(it.message)
}
)
getCompositeSubscription().add(subscription)
}
private fun fetchFacebookAlbum(albumId: String) {
val subscription = socialPhotosViewModel.getFacebookAlbumFromId(albumId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
state = it
},
{
Timber.e(it.message)
}
)
getCompositeSubscription().add(subscription)
}
private fun fetchInstagramPhotos(count: Int) {
val subscription = socialPhotosViewModel.getInstagramPhotos(count)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
state = it
},
{
Timber.e(it.message)
}
)
getCompositeSubscription().add(subscription)
}
@AdamMc331
Copy link
Author

Maybe I can do:

    private fun fetchInstagramPhotos(count: Int) {
        subscribeTo(socialPhotosViewModel.getInstagramPhotos(count))
    }

    private fun <T: SocialPhotoUploadState> subscribeTo(observable: Observable<T>) {
        val subscription = observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((
                        {
                            state = it
                        },
                        {
                            Timber.e(it.message)
                        }
                )

        getCompositeSubscription().add(subscription)
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment