亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

合并到 Observables / Singles 的方式有哪些?

合并到 Observables / Singles 的方式有哪些?

Helenr 2023-06-14 10:31:54
我有這段代碼:public void testGetBlob() throws RequestException {    TestData.getNewApplication().flatMap(testApplication -> {        Client.initialize(testApplication.getAppId(), testApplication.getApiToken(), testApplication.getMasterKey());        assertNotNull(testApplication.getApiToken());        assertNotNull(testApplication.getAppId());        assertNotNull(testApplication.getMasterKey());        Entity entity = new Entity("Todo");        return entity.create();    }).flatMap(entity -> entity.setBlobProperty("text", "Hello world!".getBytes("UTF-8")))            .flatMap(isSuccess -> {                if(isSuccess) {                    // need to access `entity` at this point                    return Single.just(isSuccess);                } else {                    return Single.just(false);                }            }).subscribe(success -> {        Browser.getWindow().getConsole().log("Blob created");        finishTest();    }, error -> {        Browser.getWindow().getConsole().error(error.getMessage());        fail();    });    delayTestFinish(5000);}在上面的代碼中,我需要做的是能夠訪問entity注釋中的對象。如何做呢?
查看完整描述

1 回答

?
LEATH

TA貢獻1936條經驗 獲得超7個贊

在一個運算符和另一個運算符之間,您只能發出一種對象類型。在您的情況下,您正在發出一個布爾值,但您還希望能夠訪問 Entity 對象。解決方案是將兩個值(實體對象和布爾值)包裝在一個類中并發出該類。


創建一個類來包裝 Entity 的發射和 setBlobProperty 的結果。


? ? class Pair {

? ? ? ? private final Entity entity;

? ? ? ? private final boolean success;


? ? ? ? private Pair(Entity entity, boolean success) {

? ? ? ? ? ? this.entity = entity;

? ? ? ? ? ? this.success = success;

? ? ? ? }


? ? ? ? public Entity getEntity() {

? ? ? ? ? ? return entity;

? ? ? ? }


? ? ? ? public boolean isSuccess() {

? ? ? ? ? ? return success;

? ? ? ? }

? ? }

然后更改您的代碼以發出該類:


public void testGetBlob() throws RequestException {

? ? TestData.getNewApplication().flatMap(testApplication -> {

// ...

? ? ? ? return entity.create();

? ? }).flatMap(entity ->?

? ? ? ? entity.setBlobProperty("text", "Hello world!".getBytes("UTF-8"))

? ? ? ? ? ? // 1. Flat map the setBlobProperty call and emit a Pair with the entity and result

? ? ? ? ? ? .flatMap(isSuccess -> Single.just(new Pair(entity, isSuccess)))

? ? )

? ? ? ? ? ? .flatMap(pair -> {

? ? ? ? ? ? ? ? if(pair.isSuccess()) {

? ? ? ? ? ? ? ? ? ? // 2. entity is available here via pair.getEntity()

? ? ? ? ? ? ? ? ? ? return Single.just(isSuccess);

? ? ? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? ? ? return Single.just(false);

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }).subscribe(success -> {

// ...

? ? }

}

Ps:不要創建自己的 Pair 類,而是檢查此線程中的選項之一。如果您使用的是 Kotlin,則有一個Pair類。



查看完整回答
反對 回復 2023-06-14
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號