Search code examples
kotlinrx-kotlin

rx kotlin subscription not working, not receiving items


I created a function which returns an Observable<String> with file names, but I don't get any event in my subscription where I call this method. Also there is no call of onError, or onComplete
See my code:

fun getAllFiles(): Observable<String> {

    val allFiles = File("/Users/stephan/Projects/Playground/kotlinfiles/")
            .listFiles { file -> !file.isDirectory() }
    return observable { subscriber ->
        allFiles.toObservable()
                .map { f -> "${f.name}" }
                .doOnNext { println("Found file $it") }
                .subscribe { subscriber}
    }
}

fun test() {
    getAllFiles()
            .doOnNext { println("File name$it") }
            .subscribe(
                    {n -> println("File: $n")},
                    {e -> println("Damn: $e")},
                    {println("Completed")})
}

Though everything is being called in the getAllFiles() function, so what am I missing?


Solution

  • observable is for creating an Observable from scratch but you already have Observable<String> from toObservable() so you don't need it. The code below works for me:

    fun getAllFiles(): Observable<String> {
      val allFiles = File("/Users/stephan/Projects/Playground/kotlinfiles/")
        .listFiles { file -> !file.isDirectory }
      return allFiles.toObservable()
        .map { f -> "${f.name}" }
    }
    
    fun test() {
      getAllFiles()
        .doOnNext { println("File name $it") }
        .subscribe(
            { n -> println("File: $n") },
            { e -> println("Damn: $e") },
            { println("Completed") })
    }
    

    You can also fix this by changing from:

    .subscribe{subscriber}
    

    to

    .subscribe(subscriber)
    

    but this nested Observable version is confusing to me.