1
  1. rxjava mSubscription.unsubscribe onCreate 的工作方式是否与活动中的 onDestroy 相同?

  2. 它是否会以相同的方式工作并取消订阅以通过将其放置在 onCreate 中来防止内存泄漏,subscription.subscribeOn().observeOn().subscribe().unsubscribe 因为不断调用 Activity 来填充下一个片段并弹回堆栈。如果 mSubscription.unsubscribe 在 Activity 的 onDestroy 中完成,它会给出一个 RunTimeException: Unable to destroy activity because of NullPointerException

  3. 我在这里错过了一些生命周期问题吗?

谢谢!

    private ViewPager viewPager;
    private TabLayout tabLayout;
    private int mPosition;
    private String id;
    private Subscription mSubscription;
    private Context mContext;
    private RealmResults<Experience> realmResults; 
    private String animateExtraColumnName, tag;
    private Boolean automaticUpdate, animateResults;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_employment);

        User currentUser = AppDelegate.getCurrentUser();
        assert currentUser != null;
        mEmployee = getRealm().where(Employee.class).equalTo("user.id", currentUser.getId()).findFirst();


            //Server returns Experience's ID
            if (employeeExperience == null) {

                AccessToken accessToken = currentUser.getAccessTokenAsTokenType(AppDelegate.getContext(), "Bearer");
               employeeExperienceAPIOAuth2Call apiCall = new employeeExperienceAPIOAuth2Call(AppDelegate.getContext(), accessToken);

                Observable<ResponseEmployeeExperience> postEmployeeExperienceObservable = apiCall.postEmployeeExperiencesRX();

                mSubscription = postEmployeeExperienceObservable
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe((data) -> {
                            Log.d(TAG, "onCreate: Subscribe ");
                         employeeExperience = data.getEmployeeExperience();
                            Log.d(TAG, "onCreate: employeeExperience.getId()");

                            getRealm().beginTransaction();
                            getRealm().copyToRealmOrUpdate(employeeExperience);
                            // This adds the new employeeExperience object into the EmployeeExperiences RealmList
                            employee.employeeExperiences.add(employeeExperience);
                            getRealm().commitTransaction();
                            getRealm().close();

                            //unsubscribe here because the activity doesnt close itself to begin with?
                            mSubscription.unsubscribe();
                            Log.d(TAG, "onCreate: Unsubscribe: ");

                            // prepare data needed by our fragment
                            FragmentAddOrUpdateEmploymentHistory addEmploymentHistoryFragment = new FragmentAddOrUpdateEmploymentHistory();

                            FragmentManager fm = getSupportFragmentManager();
                            fm.beginTransaction().replace(R.id.edit_frame_layout, addEmploymentHistoryFragment, "EDIT_FRAGMENT").commit();

                        }, (error) -> {
                            // TODO do whatever error handling we need to do here
                            Log.d(TAG, "onCreate: postEmployeeExp error");
                            error.printStackTrace();
                        });
            }

        } else if (employee.getEmployeeExperiences() != null) {
            employeeExperience = getRealm().where(employeeExperience.class).equalTo("id", id).findFirst();

            FragmentAddOrUpdateEmploymentHistory addEmploymentHistoryFragment = new FragmentAddOrUpdateEmploymentHistory();

            FragmentManager fm = getSupportFragmentManager();
            fm.beginTransaction().replace(R.id.edit_frame_layout, addEmploymentHistoryFragment, "EDIT_FRAGMENT").commit();
        }

        ImageButton checkButton = (ImageButton) findViewById(R.id.edit_toolbar_check);
        checkButton.setOnClickListener(this);

        ImageButton crossButton = (ImageButton) findViewById(R.id.edit_toolbar_cross);
        crossButton.setOnClickListener(this);

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onClick(View view) {

        Fragment editFragments = getSupportFragmentManager().findFragmentByTag("EDIT_FRAGMENT");

        switch (view.getId()) {

            case R.id.edit_toolbar_check:
                if (editFragments instanceof FragmentEditDate) {
                    Log.d(TAG, "onClick: editdate ");
                    getSupportFragmentManager().popBackStack();
                } else if (editFragments instanceof FragmentSalary){
                    Log.d(TAG, "onClick: salary ");
                    getSupportFragmentManager().popBackStack();
                } else if (editFragments instanceof FragmentAddOrUpdateEmploymentHistory) {
                    Log.d(TAG, "onClick: employmenthistory ");
                    finish();
                } else if (editFragments instanceof FragmentSingleChoice) {
                    Log.d(TAG, "singlechoice  " );
                    getSupportFragmentManager().popBackStack();
                }
                else if (editFragments instanceof FragmentMultipleChoice) {
                    Log.d(TAG, "multiplechoice  " );
                    getSupportFragmentManager().popBackStack();
                }
                break;


            case R.id.edit_toolbar_cross:
                if (editFragments instanceof FragmentAddOrUpdateEmploymentHistory) {

                            getRealm().beginTransaction();
                            employeeExperience.DELETE();
                            getRealm().commitTransaction();
                            getRealm().close();
                        }
                        finish();
                    } else {
                        finish();

                    }
                } else {
                    getSupportFragmentManager().popBackStack(); }
                break;

        }
    }
4

1 回答 1

0

简而言之 - 一旦您订阅了一个,Observable您就可以接收并响应来自它的通知 ( onNext, onError, onComplete)。同样在大多数情况下(对于冷 Observables),这实际上是Observable开始发射项目的触发点。

Unsubscribing来自 Observable 意味着您不再有兴趣接收任何进一步的通知。当您不再想接收任何东西时,您需unsubscribe要这样做,类似于如何在 Activity 的onDestroy()方法中释放任何资源。当然,与活动生命周期的平行只是为了比较 - 订阅/取消订阅过程是完全独立的事情。

您可以详细了解[这里][1] [1]的含义subscribing和含义: http ://reactivex.io/documentation/contract.htmlunsubscribing

也就是说,对您的代码的具体建议很少:

您目前在 Android 的主线程上执行了太多操作。我建议将所有与真实相关的东西作为 RX 链的一部分移动,而不是onNext()subscribe(...). 这样,它将在io线程上执行。就像是:

...
mSubscription = postEmployeeExperienceObservable
            .subscribeOn(Schedulers.io())
            .doOnNext(data -> saveDataToRealm(data))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe((data) -> {
                // prepare data needed by our fragment
                FragmentAddOrUpdateEmploymentHistory addEmploymentHistoryFragment = new FragmentAddOrUpdateEmploymentHistory();

                FragmentManager fm = getSupportFragmentManager();
                fm.beginTransaction().replace(R.id.edit_frame_layout, addEmploymentHistoryFragment, "EDIT_FRAGMENT").commit();

            }, (error) -> {
                // TODO do whatever error handling we need to do here
                Log.d(TAG, "onCreate: postEmployeeExp error");
                error.printStackTrace();
            });
}

private Data saveDataToRealm(Data data) {
    employeeExperience = data.getEmployeeExperience();
    Log.d(TAG, "onCreate: employeeExperience.getId()");

    getRealm().beginTransaction();
    getRealm().copyToRealmOrUpdate(employeeExperience);
    // This adds the new employeeExperience object into the EmployeeExperiences RealmList
    employee.employeeExperiences.add(employeeExperience);
    getRealm().commitTransaction();
    getRealm().close();
}

就取消订阅而言 - 如果您真的想unsubscribeonNext()事件中取消订阅,更好的策略是通过 a 订阅Subscriber<Data>,然后使用它的unsubscribe()方法。换句话说 - 你不会打电话mSubscription.unsubscribe(),而是this.unsubscribe()

mSubscription = postEmployeeExperienceObservable
            .subscribeOn(Schedulers.io())
            .doOnNext(data -> saveDataToRealm(data))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Data>() {

                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(Data data) {
                    ...
                    this.unsubscribe();
                }
            });

综上所述,我认为您实际上并不需要unsubscribeonNext()您的情况下的方法中进行操作,而是您可以在 中这样做onDestroy(),当然检查是否先前创建了订阅:

@Override
protected void onDestroy() {
    super.onDestroy();
    if (mSubscription != null) {
        mSubscription.unsubscribe();
    }
}
于 2017-01-18T15:24:48.097 回答