RxJava回调

时间:2016-02-15 08:22:47

标签: android rx-java

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

我已在refreshList()的{​​{1}}中致电OnCreateActivity已多次调用subscriber.onNext()getApps()已调用subscriber.onCompleted()。之后调用了onNext callbak(在refreshList()中实现)。 public void onNext(List<AppInfo> appInfos)

我徘徊为什么在调用onNext()实际调用时没有调用subscriber.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();
        }
    });
}

1 个答案:

答案 0 :(得分:1)

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