0

I have the following JSON:

{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
    "LTC": {
        "Id": "3808",
        "Url": "/coins/ltc/overview",
        "ImageUrl": "/media/19782/ltc.png",
        "Name": "LTC",
        "CoinName": "Litecoin",
        "FullName": "Litecoin (LTC)",
        "Algorithm": "Scrypt",
        "ProofType": "PoW",
        "SortOrder": "2"
    }
    ...
},
"Type": 100

}

In order for Moshi to parse the data JSON object, since it's a dynamic list, I have created a class:

data class Data(@Json(name = "Data") val cryptoCoinMap: Map<String, CryptoCoin>)

The problem is that I want to show a list of CryptoCoin using a RecyclerView adapter, so I would rather just show a List, and not a Map. I have been trying to come up with a solution in RxJava, to be able to modify in the CryptoCoin model an have the Data val be a List rather than a Map, but unfortunately I'm stuck. Does anybody have a better approach or idea about how to improve this?

This is what I have come up with so far:

var cryptoCoinList = mutableListOf<CryptoCoin>()
    coinRepository
            .getCoinList()
            .concatMapIterable { t: CryptoCoinList -> t.data.cryptoCoinMap.toList() }
            .map { t: Pair<String, CryptoCoin> -> cryptoCoinList.add(t.second) }
            // INSERT TRANSFORMATION HERE
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeBy(onNext = {
                coinListData.postValue(it.second)
            })

Thanks a lot in advance!

Jayson Minard
  • 84,842
  • 38
  • 184
  • 227
noloman
  • 11,411
  • 20
  • 82
  • 129
  • Isn't there a `cryptoCoinMap.values()` method in Kotlin? If so, just replace `map` with RxJava's `toList()` and you'll get a list. – akarnokd Feb 17 '18 at 18:01
  • You could also just pass the map as-is to a custom adapter and iterate over `map.values() ` – OneCricketeer Feb 17 '18 at 18:03
  • please note that my original question was not how to convert from `Map` to `List`, but how to do that in an underlying data set, inside our original data model, which is composed of other models plus the `Map` – noloman Feb 18 '18 at 09:44
  • I see it has been closed as duplicate, even tho as I commented right above, the linked question is NOT the same. Thanks @cricket_007 – noloman Mar 31 '18 at 10:58
  • Well, I can't reopen. Besides, it wasn't really clear what data you're trying to get in a list compared to the map. A list of key value pairs? Only the map values? What's wrong with `new ArrayList(t.data.cryptoCoinMap.values())`, as the other post says? – OneCricketeer Mar 31 '18 at 21:10

0 Answers0