0

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

I tried this

prepareMutableLiveData.value = conversationCount + prepareMutableLiveData.value

it gives error

Type mismatch.
Required:
ConversationCount
Found:
List<ConversationCount>
Kotlin Learner
  • 3,995
  • 6
  • 47
  • 127
  • `conversationCount` is already a List . So you can simply use `prepareMutableLiveData.value = conversationCount + prepareMutableLiveData.value`. See if that works .. may be some casting required – ADM Jan 14 '22 at 09:43

1 Answers1

1

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.

ADM
  • 20,406
  • 11
  • 52
  • 83