我有一个简单的场景,我会零碎地做一些事情,当我收到LiveData时,我想在Activity中做某事。
ViewModel:
class MyViewModel(application: Application) : AndroidViewModel(application) {
...
fun getUser(id: String): LiveData<User> {
return repository.getUser(id)
}
}
片段:
class MyFragment : Fragment() {
private lateinit var myViewModel: MyViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activity?.run {
myViewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
} ?: throw Exception("Invalid Activity")
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
button.setOnClickListener {
showProgressBar()
myViewModel.getUser(editText.text.toString()).observe(this, Observer { it ->
//TODO
})
}
}
}
活动:
class MainActivity : AppCompatActivity() {
private lateinit var myViewModel: MyViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myViewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
//Here I would like to observe the user instance returned from the getUser() method
}}
所以我遇到的问题是,我想在LiveData<User>
中有一个MyViewModel
的实例,以便可以在Activity和Fragment中观察它。我该如何实现?
答案 0 :(得分:0)
在MyViewModel类创建中
val userLiveData =MutableLiveData<User>()
和吸气剂
fun getUserLiveData(id: String): MutableLiveData<User> {
return userLiveData
}
fun getUser(id: String){
val disposableUser = repository.getUser(id)
.subscribe({
userLivedata.postValue(it)
})
}
在活动或片段中被称为
myViewModel.getUserLiveData.observe(this, Observer { it ->
//TODO
})
myViewModel.getUser(...)
现在在ViewModel中,您有了对象User(userLiveData.getValue())
答案 1 :(得分:0)
在活动doSomethingWithUser(user: User)
中写方法
在您的实时数据中
myViewModel.getUser(editText.text.toString()).observe(this, Observer { it ->
(requireActivity() as MainActivity).doSomethingWithUser(it)
})