2
\$\begingroup\$

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?

\$\endgroup\$
  • 1
    \$\begingroup\$ I feel as though the doubly nested switchMap/flatMap/flatMap is probably indicative of poor design. - you didn't explain it so without knowing your reasoning behind it, it's hard to comment on it. It'd be great if you could explain why you need all this chains and calls etc. It's not understandable as-is. \$\endgroup\$ – t3chb0t Apr 12 at 7:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.