Home > other >  Can't get search data from ViewModel to Activity Kotlin
Can't get search data from ViewModel to Activity Kotlin

Time:11-04

I'm trying to get my data from my ViewModel to my MainActivity.

I know that what I'm doing in my MainActivity is very wrong, but I can't seem to configure it in a way that will get the data into the MainActivity. It's just a simple string.

ViewModel

class MovieSearchViewModel : ViewModel() {
    var searchTerm = ""

    fun getSearchTerm(query: String) {
        searchTerm = query
    }
}

MainActivity

open class MainActivity : AppCompatActivity() {
    private val viewModel: MovieSearchViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)

         var searchTerm = viewModel.searchTerm
    }
}

CodePudding user response:

View Model

you can use LiveData to always get the latest data in Activity

var searchTerm = MutableLiveData("")
fun setSearchTerm(query: String){
    searchTerm.value = query
}

MainActivity

in observe it will always run every time there is a data change

viewModel.searchTerm.observe(this){
     Log.e("tag", it)
}

or

if you want get the data manually without observe you can do like this

var data = viewModel.searchTerm.value
  • Related