2016-11-07 83 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不应该被重复使用 - 订阅每一次与新的并告诉我们你得到什么