androidkotlinandroid-livedatansmutabledata

Parse Mutable Live Data to Array in Kotlin


There is a mutableLiveData Holding 2 array "deal" and "category" I need to parse this both in different adapters.

Is there a way I can convert 1 mutable live data to 2 array and then parse them to two different adapters

Suppose There is MutableVariable Name se

private lateinit var mHomePojo: MutableLiveData<List<HomePojo>>

having parse Json as below

 {
   "status": 0,
   "response": "success",
   "category": [
     {
       "categoryName": "demo",
       "categoryDesc": "demo"
     },
     {
       "categoryName": "demo1",
       "categoryDesc": "demo"
     }
   ],
   "deal": [
     {
       "dealImg": "https://aiotechnology.in/Aditechweb/upload/153102117.jpg",
       "dealDesc": "gd",
       "dealStartDate": "2019-10-18",
       "dealEndDate": "2019-10-19"
     }
   ]
 }

Is there any way to parse private lateinit var mHomePojo: MutableLiveData<List<HomePojo>> to lateinit var mDealModel: MutableLiveData<List<DealModel>> and lateinit var mCategoryModel: MutableLiveData<List<CategoryModel>>

I am new to MVVM please help


Solution

  • I think Transformations might be able to help you separate your home live data to two separate livedata object with specified properties. below is piece of code for this. (NOTE : not used lateinit var for example)

    private val homeLiveData: LiveData<HomePojo> = MutableLiveData<HomePojo>()
    
    //Category Live data
    private val categoryPojo = Transformations.map(homeLiveData) {
        it.category
    }
    
    //Deal live data
    private val dealPojo = Transformations.map(homeLiveData) {
        it.deal
    }
    
    data class HomePojo(
       /*-- Other fields --*/
       val category: List<CategoryPojo>? = null,
       val deal: List<DealPojo>? = null)
    
    
    data class CategoryPojo(
        val categoryName: String? = null,
        val categoryDesc: String? = null)
    
    data class DealPojo(
        val dealImg: String? = null,
        val dealDesc: String? = null,
        val dealStartDate: String? = null,
        val dealEndDate: String? = null)