我在这里遇到了两个代码问题,
-
如何创建一个可以观察单个数组项而不是整个数组的观察者。
-
AndroidSchedulers.mainThread((正在引发错误
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val greetings = arrayOf("Hello A", "Hello B", "Hello C") val observable = Observable.fromArray(greetings) val observer = object: DisposableObserver<Array<String>>() { override fun onNext(t: Array<String>?) { println(t) } override fun onError(e: Throwable?) { } override fun onComplete() { } } observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(observer)
}
来自#2 的错误
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fromarraydemo, PID: 11002
java.lang.NoSuchMethodError: No static method metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite; in class Ljava/lang/invoke/LambdaMetafactory; or its super classes (declaration of 'java.lang.invoke.LambdaMetafactory' appears in /apex/com.android.art/javalib/core-oj.jar)
at io.reactivex.rxjava3.android.schedulers.AndroidSchedulers.<clinit>(AndroidSchedulers.java:33)
at io.reactivex.rxjava3.android.schedulers.AndroidSchedulers.mainThread(AndroidSchedulers.java:44)
at com.example.fromarraydemo.MainActivity.onCreate(MainActivity.kt:36)
尝试#1
val observer = object: DisposableObserver<String>() {
override fun onNext(t: String?) {
TODO("Not yet implemented")
}
override fun onError(e: Throwable?) {
TODO("Not yet implemented")
}
override fun onComplete() {
TODO("Not yet implemented")
}
}
但是CCD_ 1有问题
Type mismatch: inferred type is <no name provided>! but Observer<in Array<String>!>! was expected
关于错误#1,我认为有一个函数
val observable = greetings.toObservable()
它似乎做了你想要的(与你的尝试DisposableObserver<String>
一起使用(
关于错误#2,我复制粘贴了你的代码,在AndroidSchedulers.mainThread((上没有收到任何错误,但我使用的是rxjava2,所以这不是完全相同的情况。(我在这里做的唯一更改是从String和Throwable中删除可选项(
如果您找不到更好的解决方案,那么返回rxjava2可能是一种选择?
Based on @AppDeveloper's comment,
"i mean i want to iterate through all values for the array and want on observe each one on the 'onNext'"
您可以使用fromIterable()
弹出此数组中的每个值,并在onNext((上观察每个值fromArray()
是弹出整个阵列。
Observable.fromIterable(arrays)
.subscribeOn(SchedulerProvider.io())
.observeOn(SchedulerProvider.mainThread())
.subscribe(
{TODO("do on Next")},
{TODO("do on Error")}
)