我已经尝试理解rxJava Observable超过一天了,但是我只是想不出我需要什么。我想是因为我不是在创建Observable,而是仅从API调用中返回一个Observable,并且我需要的是Observable类型的类,因此我可以使用该类的对象属性。

这是我的代码,但是当我运行print语句时,它会被完全跳过。如何使用包装在观察器中的对象属性?

// Define woman friend by creating their own large person group person.
// Returns an Observable<Person>.
rx.Observable<Person> personW = client.largePersonGroupPersons()
    .createAsync(largePersonGroupId, new CreateLargePersonGroupPersonsOptionalParameter().withName("Woman"));
System.out.println("Creating Large Person Group Person called ");
personW.subscribe(response -> System.out.print(response.name()));

最佳答案

如果从main()函数调用此代码,则看不到日志,我认为此函数createAsync(..)在后台线程中起作用,因此要返回主线程,您必须具有两个选项。

干净的是使用ObserveOn()
所以代码会像这样

    rx.Observable<Person> personW = client.largePersonGroupPersons()
    .createAsync(largePersonGroupId, new CreateLargePersonGroupPersonsOptionalParameter().withName("Woman"))
.observeOn(mainthread())//get result in the main thread
        .subscribe(result -> {
            System.out.println("Creating Large Person Group Person called ");
    })


mainthread()应该返回一个调度程序,供您确定,在Android中,我们通过observeOn(AndroidSchedulers.mainThread())

第二种选择是按照您提到的那样放置blockingGet(),但这将冻结线程

关于java - Observable <T>中带有subscribe()的对象不打印值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58551350/

10-16 01:20