简体   繁体   中英

Where should I subscribe with Rxjava in MVVM android app?

LCUser user = new LCUser();
...
user.signUpInBackground().subscribe(new Observer<LCUser>() {

    public void onSubscribe(Disposable disposable) {}

    public void onNext(LCUser user) {
        // Sign up Successful
    }

    public void onError(Throwable throwable) {
        // Sign up Failed
    }

    public void onComplete() {}
});

I'm just getting started with MVVM architecture and Rxjava, I don't know where should I place the above code (use to sign up a user). Should be ViewModel, Activity, or any other place? I want to show the result to user after getting the it.

You should subscribe this method in ViewModel because it has orientation independent lifecycle. You can dispose in onCleared method of view model to to stop background operation. It's best practice too, subscribing Rx subscriber in view model, and for coroutine to launch in view model in view model scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM