gpt4 book ai didi

android - 从 RxJava1 迁移到 RxJava2

转载 作者:搜寻专家 更新时间:2023-11-01 09:38:14 25 4
gpt4 key购买 nike

我正在查看用 MVP ( link here) 编码的 Android 应用程序示例。但是现在我想将教程中给定的 RxJava1 代码重新编码为 RxJava2 代码。但是,我遇到了麻烦,尤其是 unSubscribe()isUn​​Subscribed()。我试着转换它,我会分享我的尝试。

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 的概念还很陌生。如果有人能指出我的错误并指导我,那就太好了。 :)

最佳答案

对于迟到的答复,我深表歉意。一直忙得不可开交。正如@akarnokd 所述,与 RxJava1 相比,RxJava2 中发生了很多变化。有兴趣的可以看看这个video .

就上面的问题而言,我们可以通过使用DisposableObservables

来达到同样的效果

这是对上述问题的回答。我已经对其进行了测试并且它有效。

public void doLogin(AuthCredentials credentials) {
myDisposableObserver = new DisposableObserver<Account>() {
@Override
public void onNext(Account account) {
eventBus.post(new LoginSuccessfulEvent(account));
}

@Override
public void onError(Throwable e) {
if (isViewAttached()) {
getView().showError();
}
}

@Override
public void onComplete() {
if (isViewAttached()) {
getView().loginSuccessful();
}
}
};

// do login
accountManager.doLogin(credentials)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
}

private void cancelSubscriptionToMyPrescriptorManager() {
if (myDisposableObserver != null && !myDisposableObserver.isDisposed()) {
myDisposableObserver.dispose();
}
}

关于android - 从 RxJava1 迁移到 RxJava2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com