没有使用subscribeWith的结果。-RX Java Android

Dev*_*wal 0 android rx-java2

这是我的代码段。

@Override
public void onDestroy() {
    super.onDestroy();
    disposableSingleObserver.dispose();
}

/**
 * fetches json by making http calls
 */
private void fetchContacts() {


    disposableSingleObserver = new DisposableSingleObserver<List<Contact>>() {
        @Override
        public void onSuccess(List<Contact> movies) {
            //Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();
            contactList.clear();
            contactList.addAll(movies);
            mAdapter.notifyDataSetChanged();

            // Received all notes
        }

        @Override
        public void onError(Throwable e) {
            // Network error
        }
    };

    // Fetching all movies
    apiService.getContacts()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(disposableSingleObserver);
}
Run Code Online (Sandbox Code Playgroud)

我收到警告,未使用subscribeWith的结果。

解决此问题的正确方法是什么?

San*_*iya 8

当您使用时subscribeWith(),它Disposable会自行返回自己,您可以根据需要随时通过它来处置订阅。这样一来,您就无需创建用于将其存储在变量中以供以后处理的一次性用品。您可以执行以下操作:

// Declare global disposable variable
private CompositeDisposable mDisposable = new CompositeDisposable();

// Then add the disposable returned by subscribeWith to the disposable
mDisposable.add(apiService.getContacts()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeWith(disposableSingleObserver));
Run Code Online (Sandbox Code Playgroud)

并且在任何时间点,如果您想取消API调用,则可以像在onDestroy()中那样简单地进行调用 mDisposable.clear();

要么

更类似于您当前的操作方式:(请注意,的结果subscribeWith()直接分配给了disposableSingleObserver变量

disposableSingleObserver = apiService.getContacts()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableSingleObserver<List<Contact>>() {
                @Override
                public void onSuccess(List<Contact> movies) {
                    //Toast.makeText(getActivity(), "Success", Toast.LENGTH_SHORT).show();
                    contactList.clear();
                    contactList.addAll(movies);
                    mAdapter.notifyDataSetChanged();

                    // Received all notes
                }

                @Override
                public void onError(Throwable e) {
                   // Network error
                }
         });
Run Code Online (Sandbox Code Playgroud)

onDestroy像现在一样处理它:

@Override
public void onDestroy() {
    super.onDestroy();
    disposableSingleObserver.dispose();
}
Run Code Online (Sandbox Code Playgroud)