0

For example, I use retrofit in viewModel to make network requests, and now it always prompts The result of subscribe is not used. When I use the viewModel, considering that multiple fragments/activity may use the same viewModel object, I don't want to add onCreate and onDestroy to the viewModel to bind the life cycle with the activity/fragment, but sometimes the associated life cycle will bring more Convenient, compare the two methods separately.

For example, get the product list by click event, register the click event in the fragment, and return Observable in viewModel.getProductList().

fragment/activity onClickListener

viewModel.getProductList()?.subscribe({
                viewModel.onSuccess()
            }, {
                viewModel.onFailure(it)
            }). toComposite()

viewModel.getProductList():

fun getProductList() = Repository.device().getProductList()
            .compose(RxSchedulersHelper.ioToMain())

Use toComposite() to add dispose to the CompositeDisposable of the activity/fragment. You can actually cancel the subscription at the appropriate time. This will lose the use of databinding in onClick in the xml, and the code will be scattered in the activity/fragment.

If the activity/fragment life cycle is associated with the viewModel, just use android: onClick = "@{()-> vm.getProductList()}" in the XML. like this:

viewModel.getProductList()

Repository.device().getProductList ()
            .compose (RxSchedulersHelper.ioToMain())
            .subscribe ({
               ....
            }, {
               ...
            }).toComposite()

Then call compositeDisposable.dispose() in viewModel.onDestroy

Any suggestions? Thank you

Jeong Woo
  • 65
  • 1
  • 9

0 Answers0