Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prepend list in kotlin

Hey I want to prepend item in list in kotlin. I am trying to add item but unfortunately, I am getting error, can someone guide me how to do that.

val prepareMutableLiveData: MutableLiveData<List<ConversationCount>> = MutableLiveData(
            emptyList()
        )

fun formatData() {
        val conversationCount = mutableListOf<ConversationCount>()
        viewModelScope.launch {
            dateRange.forEachIndexed { index, dateRangeValue ->
                val findData = data?.find {
                    dateRangeValue == it.dateObject
                }
                conversationCount.add(
                    ConversationCount(
                        setDay(dateRangeValue),
                        index,
                        findData != null
                    )
                )
            }
            prepareMutableLiveData.value = mutableListOf(conversationCount) + prepareMutableLiveData.value
        }
    }

I am getting error

Type mismatch.
Required:
ConversationCount
Found:
List<ConversationCount>?
Type mismatch.
Required:
List<ConversationCount>?
Found:
List<List<ConversationCount>?>
Type mismatch.
Required:
ConversationCount
Found:
MutableList<ConversationCount

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried this

prepareMutableLiveData.value = conversationCount + prepareMutableLiveData.value

it gives error

Type mismatch.
Required:
ConversationCount
Found:
List<ConversationCount>

>Solution :

Since conversationCount is already a List and your live data is also a list i.e MutableLiveData<List<ConversationCount>> you can simply use the code below .

prepareMutableLiveData.value = conversationCount + prepareMutableLiveData.value.orEmpty()

orEmpty() here is for null safety . you can also use !! but its not safe.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading