Search in sources :

Example 1 with LoadMoreOp

use of com.tmall.wireless.tangram.op.LoadMoreOp in project Tangram-Android by alibaba.

the class CardLoadSupport method asDoLoadMoreFinishConsumer.

/**
 * Combine with {@link #observeCardLoadingMore()}, use this method as success consumer to subscribe to the Observable.<br />
 * If your request success, provide a {@link LoadMoreOp} with original card, non-empty List<BaseCell> and boolean value to indicate whether there is more.<br />
 * Otherwise, provide a {@link LoadMoreOp} with original card, empty List<BaseCell> and boolean value to indicate whether there is more.
 * @return A consumer to consume load more event.
 */
public Consumer<LoadMoreOp> asDoLoadMoreFinishConsumer() {
    return new Consumer<LoadMoreOp>() {

        @Override
        public void accept(LoadMoreOp result) throws Exception {
            Card card = result.getArg1();
            card.loading = false;
            card.loaded = true;
            List<BaseCell> cells = result.getArg2();
            boolean hasMore = result.getArg3();
            if (cells != null && !cells.isEmpty()) {
                if (card.page == sInitialPage) {
                    card.setCells(cells);
                } else {
                    card.addCells(cells);
                }
                card.page++;
                card.hasMore = hasMore;
                card.notifyDataChange();
            } else {
                card.hasMore = hasMore;
            }
        }
    };
}
Also used : Consumer(io.reactivex.functions.Consumer) BaseCell(com.tmall.wireless.tangram.structure.BaseCell) LoadMoreOp(com.tmall.wireless.tangram.op.LoadMoreOp) Card(com.tmall.wireless.tangram.dataparser.concrete.Card)

Example 2 with LoadMoreOp

use of com.tmall.wireless.tangram.op.LoadMoreOp in project Tangram-Android by alibaba.

the class RxTangramActivity method onCreate.

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mActivityLFEventLifeCycleProvider.emitNext(ActivityLFEvent.CREATE);
    setContentView(R.layout.main_activity);
    recyclerView = (RecyclerView) findViewById(R.id.main_view);
    // Step 1: init tangram
    TangramBuilder.init(this.getApplicationContext(), new IInnerImageSetter() {

        @Override
        public <IMAGE extends ImageView> void doLoadImageUrl(@NonNull IMAGE view, @Nullable String url) {
            Picasso.with(RxTangramActivity.this).load(url).into(view);
        }
    }, ImageView.class);
    // Tangram.switchLog(true);
    mMainHandler = new Handler(getMainLooper());
    // Step 2: register build=in cells and cards
    builder = TangramBuilder.newInnerBuilder(this);
    // Step 3: register business cells and cards
    builder.registerCell(1, TestView.class);
    builder.registerCell(10, SimpleImgView.class);
    builder.registerCell(2, SimpleImgView.class);
    builder.registerCell(4, RatioTextView.class);
    builder.registerCell(110, TestViewHolderCell.class, new ViewHolderCreator<>(R.layout.item_holder, TestViewHolder.class, TextView.class));
    builder.registerCell(199, SingleImageView.class);
    builder.registerVirtualView("vvtest");
    // Step 4: new engine
    engine = builder.build();
    engine.setSupportRx(true);
    engine.setVirtualViewTemplate(VVTEST.BIN);
    engine.getService(VafContext.class).setImageLoaderAdapter(new IImageLoaderAdapter() {

        private List<RxTangramActivity.ImageTarget> cache = new ArrayList<RxTangramActivity.ImageTarget>();

        @Override
        public void bindImage(String uri, final ImageBase imageBase, int reqWidth, int reqHeight) {
            RequestCreator requestCreator = Picasso.with(RxTangramActivity.this).load(uri);
            Log.d("TangramActivity", "bindImage request width height " + reqHeight + " " + reqWidth);
            if (reqHeight > 0 || reqWidth > 0) {
                requestCreator.resize(reqWidth, reqHeight);
            }
            RxTangramActivity.ImageTarget imageTarget = new RxTangramActivity.ImageTarget(imageBase);
            cache.add(imageTarget);
            requestCreator.into(imageTarget);
        }

        @Override
        public void getBitmap(String uri, int reqWidth, int reqHeight, final Listener lis) {
            RequestCreator requestCreator = Picasso.with(RxTangramActivity.this).load(uri);
            Log.d("TangramActivity", "getBitmap request width height " + reqHeight + " " + reqWidth);
            if (reqHeight > 0 || reqWidth > 0) {
                requestCreator.resize(reqWidth, reqHeight);
            }
            RxTangramActivity.ImageTarget imageTarget = new RxTangramActivity.ImageTarget(lis);
            cache.add(imageTarget);
            requestCreator.into(imageTarget);
        }
    });
    Utils.setUedScreenWidth(720);
    // Step 5: add card load support if you have card that loading cells async
    CardLoadSupport cardLoadSupport = new CardLoadSupport();
    engine.addCardLoadSupport(cardLoadSupport);
    Observable<Card> loadCardObservable = cardLoadSupport.observeCardLoading();
    Disposable dsp6 = loadCardObservable.observeOn(Schedulers.io()).map(new Function<Card, LoadGroupOp>() {

        @Override
        public LoadGroupOp apply(Card card) throws Exception {
            Log.d("TangramActivity", "loadCardObservable in map");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            JSONArray cells = new JSONArray();
            for (int i = 0; i < 10; i++) {
                try {
                    JSONObject obj = new JSONObject();
                    obj.put("type", 1);
                    obj.put("msg", "async loaded");
                    JSONObject style = new JSONObject();
                    style.put("bgColor", "#FF1111");
                    obj.put("style", style.toString());
                    cells.put(obj);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            List<BaseCell> result = engine.parseComponent(cells);
            LoadGroupOp loadGroupOp = new LoadGroupOp(card, result);
            return loadGroupOp;
        }
    }).observeOn(AndroidSchedulers.mainThread()).subscribe(cardLoadSupport.asDoLoadFinishConsumer());
    mCompositeDisposable.add(dsp6);
    Observable<Card> loadMoreObservable = cardLoadSupport.observeCardLoadingMore();
    Disposable dsp7 = loadMoreObservable.observeOn(Schedulers.io()).map(new Function<Card, LoadMoreOp>() {

        @Override
        public LoadMoreOp apply(Card card) throws Exception {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.w("TangramActivity", "loadMoreObservable " + card.load + " page " + card.page);
            JSONArray cells = new JSONArray();
            for (int i = 0; i < 9; i++) {
                try {
                    JSONObject obj = new JSONObject();
                    obj.put("type", 1);
                    obj.put("msg", "async page loaded, params: " + card.getParams().toString());
                    cells.put(obj);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            List<BaseCell> cs = engine.parseComponent(cells);
            // mock loading 6 pages
            LoadMoreOp loadMoreOp = new LoadMoreOp(card, cs, card.page != 6);
            return loadMoreOp;
        }
    }).observeOn(AndroidSchedulers.mainThread()).subscribe(cardLoadSupport.asDoLoadMoreFinishConsumer());
    mCompositeDisposable.add(dsp7);
    engine.addSimpleClickSupport(new SampleClickSupport());
    BannerSupport bannerSupport = new BannerSupport();
    engine.register(BannerSupport.class, bannerSupport);
    Disposable dsp1 = bannerSupport.observeSelected("banner1").subscribe(new Consumer<Integer>() {

        @Override
        public void accept(Integer integer) throws Exception {
            Log.d("TangramActivity", "1 selected " + integer);
        }
    });
    mCompositeDisposable.add(dsp1);
    final Disposable dsp2 = bannerSupport.observeSelected("banner1").subscribe(new Consumer<Integer>() {

        @Override
        public void accept(Integer integer) throws Exception {
            Log.d("TangramActivity", "2 selected " + integer);
        }
    });
    mCompositeDisposable.add(dsp2);
    Disposable dsp3 = bannerSupport.observeScrollStateChanged("banner2").subscribe(new Consumer<Integer>() {

        @Override
        public void accept(Integer integer) throws Exception {
            Log.d("TangramActivity", "state changed " + integer);
        }
    });
    mCompositeDisposable.add(dsp3);
    Disposable dsp4 = bannerSupport.observeScrolled("banner2").subscribe(new Consumer<ScrollEvent>() {

        @Override
        public void accept(ScrollEvent scrollEvent) throws Exception {
            Log.d("TangramActivity", "scrolled " + scrollEvent.toString());
        }
    });
    mCompositeDisposable.add(dsp4);
    // Step 6: enable auto load more if your page's data is lazy loaded
    engine.enableAutoLoadMore(true);
    // Step 7: bind recyclerView to engine
    engine.bindView(recyclerView);
    // Step 8: listener recyclerView onScroll event to trigger auto load more
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            engine.onScrolled();
        }
    });
    // Step 9: set an offset to fix card
    engine.getLayoutManager().setFixOffset(0, 40, 0, 0);
    // Step 10: get tangram data and pass it to engine
    // method 1, use simple consumer api
    // Observable.fromCallable(new Callable<byte[]>() {
    // @Override
    // public byte[] call() throws Exception {
    // Log.d("TangramActivity", "call asset in thread " + Thread.currentThread().getName());
    // 
    // return getAssertsFile(getApplicationContext(), "data.json");
    // }
    // }).subscribeOn(Schedulers.io())
    // .observeOn(Schedulers.computation())
    // .map(new Function<byte[], String>() {
    // @Override
    // public String apply(byte[] bytes) throws Exception {
    // Log.d("TangramActivity", "to string in thread " + Thread.currentThread().getName());
    // 
    // return new String(bytes);
    // }
    // }).map(new Function<String, JSONArray>() {
    // @Override
    // public JSONArray apply(String s) throws Exception {
    // Log.d("TangramActivity", "to json in thread " + Thread.currentThread().getName());
    // return new JSONArray(s);
    // }
    // }).observeOn(AndroidSchedulers.mainThread())
    // .doOnSubscribe(new Consumer<Disposable>() {
    // @Override
    // public void accept(Disposable disposable) throws Exception {
    // Log.d("TangramActivity", "do subscribe in thread " + Thread.currentThread().getName());
    // }
    // })
    // .subscribe(engine.asOriginalDataConsumer());
    // method 2, use transformer api
    // Observable.fromCallable(new Callable<byte[]>() {
    // @Override
    // public byte[] call() throws Exception {
    // Log.d("TangramActivity", "call asset in thread " + Thread.currentThread().getName());
    // 
    // return getAssertsFile(getApplicationContext(), "data.json");
    // }
    // }).map(new Function<byte[], String>() {
    // @Override
    // public String apply(byte[] bytes) throws Exception {
    // Log.d("TangramActivity", "to string in thread " + Thread.currentThread().getName());
    // 
    // return new String(bytes);
    // }
    // }).map(new Function<String, JSONArray>() {
    // @Override
    // public JSONArray apply(String s) throws Exception {
    // Log.d("TangramActivity", "to json in thread " + Thread.currentThread().getName());
    // return new JSONArray(s);
    // }
    // }).subscribeOn(Schedulers.io())
    // .compose(engine.getDataTransformer())
    // .doOnSubscribe(new Consumer<Disposable>() {
    // @Override
    // public void accept(Disposable disposable) throws Exception {
    // Log.d("TangramActivity", "do subscribe in thread " + Thread.currentThread().getName());
    // }
    // })
    // .subscribe(engine.asParsedDataConsumer());
    // method 3, emit json array and flat map to jsonobject
    Disposable dsp8 = Observable.create(new ObservableOnSubscribe<JSONArray>() {

        @Override
        public void subscribe(ObservableEmitter<JSONArray> emitter) throws Exception {
            String json = new String(getAssertsFile(getApplicationContext(), "data.json"));
            JSONArray data = null;
            try {
                data = new JSONArray(json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            emitter.onNext(data);
            emitter.onComplete();
        }
    }).flatMap(new Function<JSONArray, ObservableSource<JSONObject>>() {

        @Override
        public ObservableSource<JSONObject> apply(JSONArray jsonArray) throws Exception {
            return JSONArrayObservable.fromJsonArray(jsonArray);
        }
    }).map(new Function<JSONObject, ParseSingleGroupOp>() {

        @Override
        public ParseSingleGroupOp apply(JSONObject jsonObject) throws Exception {
            return new ParseSingleGroupOp(jsonObject, engine);
        }
    }).compose(engine.getSingleGroupTransformer()).filter(new Predicate<Card>() {

        @Override
        public boolean test(Card card) throws Exception {
            return card.isValid();
        }
    }).map(new Function<Card, AppendGroupOp>() {

        @Override
        public AppendGroupOp apply(Card card) throws Exception {
            Thread.sleep(300);
            return new AppendGroupOp(card);
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(engine.asAppendGroupConsumer(), new Consumer<Throwable>() {

        @Override
        public void accept(Throwable throwable) throws Exception {
            throwable.printStackTrace();
        }
    });
    mCompositeDisposable.add(dsp8);
    // method 4, create from json
    // Disposable dsp5 = Observable.create(new ObservableOnSubscribe<AppendGroupOp>() {
    // @Override
    // public void subscribe(ObservableEmitter<AppendGroupOp> emitter) throws Exception {
    // Log.d("TangramActivity", "subscribe in thread " + Thread.currentThread().getName());
    // String json = new String(getAssertsFile(getApplicationContext(), "data.json"));
    // JSONArray data = null;
    // try {
    // data = new JSONArray(json);
    // } catch (JSONException e) {
    // e.printStackTrace();
    // }
    // List<Card> cards = engine.parseData(data);
    // for (int i = 0, size = cards.size(); i < size; i++) {
    // emitter.onNext(new AppendGroupOp(cards.get(i)));
    // Log.d("TangramActivity", "emitter " + i);
    // try {
    // Thread.sleep(500);
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    // emitter.onComplete();
    // }
    // }).subscribeOn(Schedulers.io())
    // .observeOn(AndroidSchedulers.mainThread())
    // .doOnComplete(new Action() {
    // @Override
    // public void run() throws Exception {
    // final BaseCell cell = (BaseCell) engine.getGroupBasicAdapter().getComponents().get(1);
    // mCompositeDisposable.add(ViewClickObservable.from(findViewById(R.id.last)).map(
    // new Function<Object, JSONObject>() {
    // @Override
    // public JSONObject apply(Object o) throws Exception {
    // cell.extras.put("title", "Rx标题2");
    // JSONObject jsonObject = cell.extras;
    // return jsonObject;
    // }
    // }).subscribe(cell.asUpdateConsumer()));
    // }
    // })
    // .subscribe(engine.asAppendGroupConsumer());
    // mCompositeDisposable.add(dsp5);
    mCompositeDisposable.add(ViewClickObservable.from(findViewById(R.id.first)).map(new Function<Object, UpdateCellOp>() {

        @Override
        public UpdateCellOp apply(Object o) throws Exception {
            BaseCell cell = (BaseCell) engine.getGroupBasicAdapter().getComponents().get(0);
            cell.extras.put("title", "Rx标题1");
            return new UpdateCellOp(cell);
        }
    }).subscribe(engine.asUpdateCellConsumer()));
    mCompositeDisposable.add(ViewClickObservable.from(findViewById(R.id.count)).subscribe(new Consumer<Object>() {

        @Override
        public void accept(Object o) throws Exception {
            dsp2.dispose();
        }
    }));
}
Also used : ArrayList(java.util.ArrayList) ParseSingleGroupOp(com.tmall.wireless.tangram.op.ParseSingleGroupOp) LoadGroupOp(com.tmall.wireless.tangram.op.LoadGroupOp) Consumer(io.reactivex.functions.Consumer) TextView(android.widget.TextView) RatioTextView(com.tmall.wireless.tangram.example.data.RatioTextView) List(java.util.List) ArrayList(java.util.ArrayList) TestViewHolder(com.tmall.wireless.tangram.example.data.TestViewHolder) Handler(android.os.Handler) Card(com.tmall.wireless.tangram.dataparser.concrete.Card) UpdateCellOp(com.tmall.wireless.tangram.op.UpdateCellOp) JSONObject(org.json.JSONObject) ScrollEvent(com.tmall.wireless.tangram.support.RxBannerScrolledListener.ScrollEvent) BannerSupport(com.tmall.wireless.tangram.support.BannerSupport) JSONObject(org.json.JSONObject) ImageBase(com.tmall.wireless.vaf.virtualview.view.image.ImageBase) AppendGroupOp(com.tmall.wireless.tangram.op.AppendGroupOp) Listener(com.tmall.wireless.vaf.virtualview.Helper.ImageLoader.Listener) BaseCell(com.tmall.wireless.tangram.structure.BaseCell) CardLoadSupport(com.tmall.wireless.tangram.support.async.CardLoadSupport) IInnerImageSetter(com.tmall.wireless.tangram.util.IInnerImageSetter) LoadMoreOp(com.tmall.wireless.tangram.op.LoadMoreOp) RequestCreator(com.squareup.picasso.RequestCreator) SampleClickSupport(com.tmall.wireless.tangram.example.support.SampleClickSupport) Function(io.reactivex.functions.Function) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONException(org.json.JSONException) IOException(java.io.IOException) VafContext(com.tmall.wireless.vaf.framework.VafContext) IImageLoaderAdapter(com.tmall.wireless.vaf.virtualview.Helper.ImageLoader.IImageLoaderAdapter) RecyclerView(android.support.v7.widget.RecyclerView) TargetApi(android.annotation.TargetApi)

Aggregations

Card (com.tmall.wireless.tangram.dataparser.concrete.Card)2 LoadMoreOp (com.tmall.wireless.tangram.op.LoadMoreOp)2 BaseCell (com.tmall.wireless.tangram.structure.BaseCell)2 Consumer (io.reactivex.functions.Consumer)2 TargetApi (android.annotation.TargetApi)1 Handler (android.os.Handler)1 RecyclerView (android.support.v7.widget.RecyclerView)1 TextView (android.widget.TextView)1 RequestCreator (com.squareup.picasso.RequestCreator)1 RatioTextView (com.tmall.wireless.tangram.example.data.RatioTextView)1 TestViewHolder (com.tmall.wireless.tangram.example.data.TestViewHolder)1 SampleClickSupport (com.tmall.wireless.tangram.example.support.SampleClickSupport)1 AppendGroupOp (com.tmall.wireless.tangram.op.AppendGroupOp)1 LoadGroupOp (com.tmall.wireless.tangram.op.LoadGroupOp)1 ParseSingleGroupOp (com.tmall.wireless.tangram.op.ParseSingleGroupOp)1 UpdateCellOp (com.tmall.wireless.tangram.op.UpdateCellOp)1 BannerSupport (com.tmall.wireless.tangram.support.BannerSupport)1 ScrollEvent (com.tmall.wireless.tangram.support.RxBannerScrolledListener.ScrollEvent)1 CardLoadSupport (com.tmall.wireless.tangram.support.async.CardLoadSupport)1 IInnerImageSetter (com.tmall.wireless.tangram.util.IInnerImageSetter)1