Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 646
Stephan Avatar asked Jan 06 '23 12:01

Stephan


1 Answers

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.

like image 85
pt2121 Avatar answered Jan 10 '23 19:01

pt2121