【问题标题】:RxJava callbackRxJava 回调
【发布时间】:2016-02-15 16:40:48
【问题描述】:

我正在阅读一本名为“RxJava Essentials”的书。以下代码来自那里。我做了一点修改。

我在Activity 中的OnCreate 中调用了refreshList()。并且subscriber.onNext() 已在getApps() 中多次调用,subscriber.onCompleted() 已被调用。之后,onNext callbak(在refreshList() 中实现)被调用。 public void onNext(List<AppInfo> appInfos)

我徘徊为什么subscriber.onNext()实际调用时不调用onNext()回调?为什么后来被调用了?

void refreshList()
{
    getApps().toSortedList()
    .subscribe(new Observer<List<AppInfo>>() 
    {
        @Override
        public void onCompleted() {
            Log.e(TAG, "onCompleted()");
        }

        @Override
        public void onError(Throwable te) {
            Log.e(TAG, "onError()");
        }

        @Override
        public void onNext(List<AppInfo> appInfos) {
            Log.e(TAG, "onNext()");

            for (AppInfo tmpInfo : appInfos)
            {
                //tmpInfo.toString();
                Log.e(TAG, String.format("tmpInfo = %s", tmpInfo.toString()));
            }
        }
    });
}


private Observable<AppInfo> getApps()
{
    return Observable.create(subscriber ->
    {
        List<AppInfoRich> apps = new ArrayList<>();

        final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);

        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> infos = getPackageManager().queryIntentActivities(mainIntent, 0);

        for (ResolveInfo info : infos)
        {
            apps.add(new AppInfoRich(this, info));
        }

        for (AppInfoRich appInfo : apps)
        {
            Bitmap icon = BitmapUtils.drawableToBitmap(appInfo.getIcon());
            String name = appInfo.getName();
            String iconPath = mFilesDir + "/" + name;

            //BitmapUtils.storeBitmap(App.instance, icon, name);

            BitmapUtils.storeBitmap(getApplicationContext(), icon, name);

            if(subscriber.isUnsubscribed())
            {
                return;
            }

            subscriber.onNext(new AppInfo(name, iconPath, appInfo.getLastUpdateTime()));

        }

        if( !subscriber.isUnsubscribed())
        {
            subscriber.onCompleted();
        }
    });
}

【问题讨论】:

    标签: android rx-java


    【解决方案1】:

    您不直接订阅您创建的 observable。您正在订阅 toSortedList operator 的结果,它将所有发出的项目收集到一个列表中,对其进行排序,然后发出该列表。

    【讨论】:

    • 感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 2016-03-27
    相关资源
    最近更新 更多