T
T
Tsuzukeru2021-02-17 16:46:14
Android
Tsuzukeru, 2021-02-17 16:46:14

How to make two Rx requests into one using flatMap?

I have the following data class:

data class MediaDetail(
   val dateCreated:String,
   val nasaId:String,
   val keywords:List<String>,
   val mediaType:String,
   val center:String,
   val title:String,
   val description:String,
   val location:String,
   var assets:Map<String,String>?
)


I have to initialize it twice. The first fetchMediaDetails() method is all val fields and null for var fields assets. And with the help of the second fetchMediaAsset() method, I initialize the assets field.

As a result, I get this Rx request. Can it be done in one method using flatMap? If so, how?

fun fetchMediaDetails(nasaId:String){
        _networkState.postValue(NetworkState.LOADING)

        try {
            compositeDisposable.add(
            apiService.mediaInfo(nasaId)
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .subscribe ({
                fetchMediaAsset(it.item)
                },{
                    _networkState.postValue(NetworkState.ERROR)
                    Log.e("MediaDetailsDataSource", it.message.toString())
                })
            )
        }
        catch (e: Exception){
            Log.e("MediaDetailsDataSource", e.message.toString())
        }
    }

    private fun fetchMediaAsset(mediaDetail: MediaDetail){
        try {
            compositeDisposable.add(
                apiService.mediaAsset(mediaDetail.nasaId)
                    .observeOn(Schedulers.io())
                    .subscribeOn(Schedulers.io())
                    .subscribe({
                        mediaDetail.assets = it.item
                        _downloadedMediaDetailsResponse.postValue(mediaDetail)
                        _networkState.postValue(NetworkState.LOADED)
                    }, {
                        Log.e("MediaDetailsDataSource", it.message.toString())
                    })
            )
        }
        catch (e: Exception){
            Log.e("MediaDetailsDataSource", e.message.toString())
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-02-17
@Tsuzukeru

So do it.

request1.flatMap{ mediaDetail ->
   request2(mediaDetail.id).map{
       mediaDetail.copy(assets=it.item)
   }
}. subscribe

It is not necessary to have mutable data in the stream, use immutable data and copy.
And for the umpteenth time I tell you, do not mix rx and mutable State.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question