设置 return 来自 Flowable 的数据在 Android 中不起作用

Set return data from Flowable not working in Android

我有这些方法:

    fun getMyObjectByCode(code: String): Flowable<Array<MyObject>> {
        return interfaceRest.getObject(code)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
    }

然后这样调用:

   fun getMyObjectByCode(Code: String): MyObject {
        var resultMyObject = MyObject()

        compositeDisposable.add(
            viewmodel.getMyObjectByCode(code).subscribe { result ->
                // just need the first element
                Log.i(TAG, "result :${result[0].toString()}")
                resultMyObject = result[0]
            }
        )

        return resultMyObject
    }

最后:

var myobject = getMyObjectByCode(code)

它工作正常,因为我可以在日志中看到正确的 MyObject,但是 return 对象从未设置值,我做错了什么?

作为一次性要求和可观察的(单流等)。您可以尝试

 Single.just(viewmodel.getMyObjectByCode(code))