Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

android - MutableLiveData value get cleared when try to filter data from its value too frequently

Scenario:

  • I'm a getting list of data from the repository
  • Updating the list to a MutableLiveData called searchedDoctorsListMLD and to observe the data by exposing another variable called searchedDoctorListLD
  • Based on the value of the searchedDoctorListLD UI is updating (RecyclerView)

Now I have to filter out some item from the searchedDoctorListLD based on the user input & update the UI (RecyclerView)

Approach 1:

    val tempResult = mutableListOf<DoctorInfoDataModel>()
    searchedDoctorListLD.value?.forEach {
        if (it.name.toLowerCase()
                .contains(
                    text.toString()
                        .toLowerCase(),
                    true
                )
        ) {
            tempResult.add(it)
        }
    }
    updateDoctorsList(tempResult)
  • First time when I search something working fine
  • When I clear the input text, UI is updated based on the searchedDoctorListLD value
    searchedDoctorListLD.value?.let {
        updateDoctorsList(it)
    }
  • So when I try to filter some item from the list again searchedDoctorListLD get cleared (searchedDoctorsListMLD also)

Approach 2:

I have tried to use a HashMap (by converting the value list (ArrayList) to HashMap) and filter out the data from the HashMap and store the data into the tempResult and update the UI

    val tempResult =
        mutableListOf<DoctorInfoDataModel>()
    val tempData: HashMap<Int, DoctorInfoDataModel> =
        HashMap()
    searchedDoctorListLD.value?.let {
        tempData.putAll(
            it.toMutableList().toHashMap()
        )
    }
    repeat(tempData.count()) { position ->
        tempData[position]?.let {
            if (it.name.toLowerCase()
                    .contains(
                        text.toString()
                            .toLowerCase(),
                        true
                    )
            ) {
                tempResult.add(it)
            }
        }
    }
    updateDoctorsList(tempResult)
  • So when I try to filter some item from the list again searchedDoctorListLD get cleared (searchedDoctorsListMLD also)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...