2016-11-07 224 views
4

我想創建Android上使用RxJava一個新的文件,如:RxJava file.createNewFile()總是返回TRUE

public Observable<Boolean> createRx(String name) { 

    return Observable.just(name) 
     .map(new Func1<String, Boolean>() { 
      @Override 
      public Boolean call(String s) { 
       File newFile = new File(localPath + "/" + s); 

       try { 
        return newFile.createNewFile(); 
       } catch (IOException e) { 
        throw Exceptions.propagate(e); 
       } 
      } 
     }); 
} 

要正常創建一個新的文件,如:

public boolean createNonRx(String name) { 

    boolean ret = false; 

    try { 
     File newFile = new File(localPath + "/" + name); 
     ret = newFile.createNewFile(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return ret; 
} 

我JUnitTest代碼和TestReport:

@Test 
public void testCreateRx() throws Exception { // FAIL! 
    TestSubscriber<Boolean> testSubscriber = new TestSubscriber<>(); 

    source.createRx("JunitTest_Create_Rx").subscribe(testSubscriber); 
    testSubscriber.assertNoErrors(); 
    testSubscriber.assertReceivedOnNext(Arrays.asList(Boolean.TRUE)); //PASS! 

    source.createRx("JunitTest_Create_Rx").subscribe(testSubscriber); 
    testSubscriber.assertNoErrors(); 
    testSubscriber.assertReceivedOnNext(Arrays.asList(Boolean.FALSE)); //FAIL! 
    //expected to be [false] (Boolean) but was: [true] (Boolean) 
} 


@Test 
public void testCreateNonRx() { // PASS! 
    boolean fstRet = source.createNonRx("JunitTest_LocalDataSource_Create_Non_Rx"); 
    assertTrue(fstRet); 

    boolean secRet = source.createNonRx("JunitTest_LocalDataSource_Create_Non_Rx"); 
    assertFalse(secRet); 
} 

我是一個新手,以RxJava,有沒有我的代碼有問題嗎?

爲什麼當我嘗試創建現有文件時,createRx()的調用返回TRUE?

感謝您的任何幫助。

回答

1

SubscribersObservers不應該被重複使用 - 訂閱每一次與新的並告訴我們你得到什麼