Knowledge Drilling
Knowledge Drilling

Reputation: 1036

RxJava callback

I'm reading a book named "RxJava Essentials". Following code is from there. and i modified a little.

I have called refreshList() in OnCreate of my Activity. and subscriber.onNext() has been called many times in getApps() and subscriber.onCompleted() has been called. After that onNext callbak (implemented in refreshList()) has been called. public void onNext(List<AppInfo> appInfos)

I wander why onNext() callback is not called when subscriber.onNext() actuall called? Why it has been called later?

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();
        }
    });
}

Upvotes: 0

Views: 248

Answers (1)

Joni
Joni

Reputation: 111219

You don't subscribe directly to the observable you have created. You are subscribing to the result of the toSortedList operator, which collects all emitted items into a list, sorts it, and then emits the list.

Upvotes: 1

Related Questions