Android implement search with view model and live data

后端 未结 5 1630
灰色年华
灰色年华 2020-12-15 01:10

I\'m working on a project in android for a udacity course I\'m currently trying to implement a search function while adhering to android architecture components and using fi

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 01:53

    I faced the same issue and solved it with the answer of @Rohit, thanks! I simplified my solution a bit to illustrate it better. There are Categories and each Category has many Items. The LiveData should only return items from one Category. The user can change the Category and then the fun search(id: Int) is called, which changes the value of a MutableLiveData called currentCategory. This then triggers the switchMap and results in a new query for items of the category:

    class YourViewModel: ViewModel() {
    
        // stores the current Category
        val currentCategory: MutableLiveData = MutableLiveData()
    
        // the magic happens here, every time the value of the currentCategory changes, getItemByCategoryID is called as well and returns a LiveData
        val items: LiveData> = Transformations.switchMap(currentCategory) { category ->
               // queries the database for a new list of items of the new category wrapped into a LiveData
               itemDao.getItemByCategoryID(category.id)
        }
    
        init {
            currentCategory.value = getStartCategoryFromSomewhere()
        }
    
        fun search(id: Int) { // is called by the fragment when you want to change the category. This can also be a search String...
            currentCategory.value?.let { current ->
                // sets a Category as the new value of the MutableLiveData
                current.value = getNewCategoryByIdFromSomeWhereElse(id)
            }
        }
    }
    

提交回复
热议问题