I am new to RxJava and have the following code which I use to search YouTube videos via the API and ultimately display them in a list.
private fun showYouTubeSearchView() {
val youtubeSearchView = viewFactory.getYouTubeSearchView(null)
val contentView = youtubeSearchView.rootView
youtubeSearchView.subscribeSearchEvent()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.switchMap { searchTerm ->
searchYouTubeUseCase.searchYouTube(searchTerm)
.flatMapIterable { youTubeSearchResults ->
youTubeSearchResults.items
}
.flatMap { item ->
getVideoStatisticsUseCase.getViewCount(item.id.videoId)
.flatMap { viewCount ->
Observable.just(
YouTubeListItemModel(
item,
viewCount
)
)
}
}
.toList()
.toObservable()
}
.observeOn(AndroidSchedulers.mainThread())
.flatMap { youTubeListItemModels ->
youtubeSearchView.showSearchItems(youTubeListItemModels)
youtubeSearchView.subscribeItemClicked()
}
.subscribe(
{ youTubeListItemModel ->
showCreateVideoClipView(youTubeListItemModel)
},
{ t ->
Snackbar.make(contentView, "Error", Snackbar.LENGTH_LONG).show()
Log.e(TAG, "error", t)
}
)
setContentView(contentView)
}
You will notice a second API call is required to get the view count for each item in the list.
I hope the code is relatively understandable as-is. I feel as though the doubly nested switchMap/flatMap/flatMap is probably indicative of poor design. Is there a better way of accomplishing the same thing?