我正在查看以MVP编码的Android应用程序示例(link here)。但是现在我想将教程中给定的RxJava1代码重新编码为RxJava2代码。但是,我遇到了问题,尤其是unSubscribe()
和isUnSubscribed()
。我试图转换它,我将分享我的尝试。
RxJava1代码:
public void doLogin(AuthCredentials credentials) {
cancelSubscription();
subscriber = new Subscriber<Account>() {
@Override public void onCompleted() {
if (isViewAttached()) {
getView().loginSuccessful();
}
}
@Override public void onError(Throwable e) {
if (isViewAttached()) {
getView().showError();
}
}
@Override public void onNext(Account account) {
eventBus.post(new LoginSuccessfulEvent(account));
}
};
// do login
accountManager.doLogin(credentials)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
private void cancelSubscription() {
if (subscriber != null && !subscriber.isUnsubscribed()) {
subscriber.unsubscribe();
}
}
这是我对RxJava2代码的尝试:
public void doLogin(AuthCredentials credentials) {
cancelSubscription();
subscriber = new Subscriber<Account>() {
@Override public void onSubscribe(Subscription s) {
// do login
accountManager.doLogin(credentials)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
@Override public void onCompleted() {
if (isViewAttached()) {
getView().loginSuccessful();
}
}
@Override public void onError(Throwable e) {
if (isViewAttached()) {
getView().showError();
}
}
@Override public void onNext(Account account) {
eventBus.post(new LoginSuccessfulEvent(account));
}
};
}
private void cancelSubscription() {
//isUnsubscribed and unsubscribe doesnt work anymore
}
我对RxJava的概念相当新。如果有人能指出我的错误并指导我那将是伟大的。 :)
答案 0 :(得分:1)
我为迟到的答案道歉。一直都很忙。正如@akarnokd所述,与RxJava1相比,RxJava2已经做了很多改变。如果您有兴趣,请查看video。
就上述问题而言,我们可以使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="">
<div class="form-group">
<label for="first">Dummy text 1</label>
<select id="first" class="mapped" select-group="first">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
</div>
<div class="">
<div class="form-group">
<select id="first" class="mapped" select-group="first">
<option>Dummy text 1</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
</div>
<div class="">
<div class="form-group">
<label for="second">Dummy text 2</label>
<select id="second" class="mapped" select-group="second">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
</div>
<div class="">
<div class="form-group">
<select id="second" class="mapped" select-group="second">
<option>Dummy text 2</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
</div>
以上是上述问题的答案。我测试了它并且它有效。
DisposableObservables