Created
February 1, 2015 12:31
-
-
Save JoanZapata/63e4696a7818a536e890 to your computer and use it in GitHub Desktop.
Experimentation with Rx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import rx.Observable | |
import java.io.File | |
/** Basic data structure to add information to a file reference. */ | |
data class FileInfo(val file: File, var bytes: Long = 0, var filesCount: Long = 1) | |
/** Main function. */ | |
fun main(args: Array<String>) { | |
Observable.just(File("/Users/joan/Dropbox")) | |
.flatMap({ fileToFileInfo(it) }) | |
.subscribe( | |
{ fileInfo -> println(fileInfo) }, | |
{ throwable -> throwable.printStackTrace() }) | |
} | |
/** Recursive function to compute additional information on a file. */ | |
fun fileToFileInfo(file: File): Observable<FileInfo> { | |
if (file.isFile()) { | |
return Observable.just(FileInfo(file, file.length())) | |
} else if (file.isDirectory()) { | |
return Observable.from(file.listFiles()) | |
.flatMap({ fileToFileInfo(it) }) | |
.reduce(FileInfo(file), { acc, b -> | |
acc.bytes += b.bytes | |
acc.filesCount += b.filesCount | |
acc | |
}) | |
} | |
return Observable.error(IllegalArgumentException("$file is neither a file or a directory")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment