如下面的代码所示,由于强制转换不正确,我在以下一行中收到一条错误消息
I am using the folloing rx versions
compile 'io.reactivex.rxjava2:rxandroid:2.0.2'
compile 'io.reactivex.rxjava2:rxjava:2.0.5'
请让我知道如何解决此问题。
注释:
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
代码:
getAnimalsObservable()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((Consumer<? super List<String>>)getAnimalsObserver());
private Observer<String> getAnimalsObserver() {
return new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
Log.i(TAG, "onSubscribe->d: " + d);
}
@Override
public void onNext(String s) {
Log.i(TAG, "onNext->s: " + s);
}
@Override
public void onError(Throwable e) {
Log.i(TAG, "onError->e: " + e);
}
@Override
public void onComplete() {
Log.i(TAG, "onComplete");
}
};
}
公共类MainActivity扩展了AppCompatActivity {
Caused by: java.lang.ClassCastException:
com.example.pc_a.myapplication.MainActivity$1 cannot be cast to
io.reactivex.functions.Consumer
at com.example.pc_a.myapplication.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:6288)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
t android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2642)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754)
logcat :
SELECT
date,
COUNT(DISTINCT(fullVisitorId)) as daily_active_user,
SUM(count(Distinct(fullVisitorId))) OVER (ORDER BY date ROWS BETWEEN 29 PRECEDING AND CURRENT ROW) AS monthly_active_user
FROM
`bigquery-public-data.google_analytics_sample.ga_sessions_2017*`,
unnest(hits) as h
WHERE
_table_suffix BETWEEN "0101" AND "0715"
GROUP BY
date
答案 0 :(得分:1)
首先,您无需强制转换为Consumer
。其次,您应该按如下方式修改Observer
使其起作用(Observer
已经可以在subscribe
中使用)。我对其进行了简化以使其更加整洁:
private Observable<List<String>> getAnimalsObservable() {
return Observable.fromArray(Arrays.asList(
new String[]{
"Ant", "Ape",
"Bat", "Bee", "Bear", "Butterfly",
"Cat", "Crab", "Cod",
"Dog", "Dove",
"Fox", "Frog"
}
));
}
private Observer<List<String>> getObserver() {
return new Observer<List<String>>() {
@Override
public void onSubscribe(Disposable d) {
//your logic here
}
@Override
public void onNext(List<String> values) {
//your logic here
for (String value : values) {
System.out.print(value + " ");
}
}
@Override
public void onError(Throwable e) {
//your logic here
}
@Override
public void onComplete() {
//your logic here
}
};
}
@Test
public void test() {
// here you can add your observeOn and subscribeOn but they're not important for the test
getAnimalsObservable()
.subscribe(getObserver());
}
输出:
蚂蚁猿蝙蝠蜜蜂熊蝴蝶猫蟹鳕鱼狗鸽子狐狸青蛙