Handle different return types in switchMap operato

2019-08-01 01:14发布

I use RxBinding and I have a case where I make use of RxTextView's textChangeEvents() I filter them and pass them to switchMap() where I execute a network request (using Retrofit) to an endpoint based on another value.

tl;dr :

switchMap(new Func1<TextViewTextChangeEvent, Observable<List<String>>>() {
                @Override
                public Observable<List<String>> call(TextViewTextChangeEvent textViewTextChangeEvent) {

                    switch (visibleTab) {
                        case TAGS:
                            return presenter.executeSearchPostsByTag(searchBarText, String.valueOf(0));
                        case PEOPLE:
                            return presenter.executeSearchPostsByPeople(searchBarText, String.valueOf(0));
                        case COMPANIES:
                            return presenter.executeSearchPostsByCompanies(searchBarText, String.valueOf(0));
                        case JOBS:
                            return presenter.executeSearchPostsByJobs(searchBarText, String.valueOf(0));
                        default:
                            return presenter.executeSearchPostsByTag(searchBarText, String.valueOf(0));
                    }

                }
            })

but I can't have as a return type : Observable<List<String>> since I receive a different object from each request.

How should I deal with such a case ?

1条回答
姐就是有狂的资本
2楼-- · 2019-08-01 01:57

One method is to use an intermediary Completable transformation to throw away all elements and just wait for the onComplete call.

For each item, add .toCompletable().<Void>toObservable() to turn the output into Observable<Void> instead of Observable<List<String>>. This works since completable ensures no elements are emitted, ensuring type-safety.

Another option that might work is declaring the output as Observable<?>, but those wildcards can cause some weird issues with generics.

Note that if you're using RxJava 2, then the call to ignore elements and just return nothing is .ignoreElements().<Void>toObservable()

查看更多
登录 后发表回答