4

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?

Stephan
  • 15,704
  • 7
  • 48
  • 63

1 Answers1

9

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.

pt2121
  • 11,720
  • 8
  • 52
  • 69
  • your answer is working, but I wonder why `toObservable()` is used in the rxkotlin examples though. https://github.com/ReactiveX/RxKotlin/blob/0.x/src/examples/kotlin/rx/lang/kotlin/examples/examples.kt#L45 – Stephan Mar 05 '16 at 23:05
  • @EarlOfEgo kinda weird. i guess that just for demonstration. if you check git history, you'll see how it's getting there. At a very first commit, it makes more sense: https://github.com/ReactiveX/RxKotlin/commit/d365846fa8502566132fd8d53b7e83aaa5bc452e#diff-3f0526ee70e691c01cb9149a4ccbca03R32 – pt2121 Mar 05 '16 at 23:44