Skip to content

Instantly share code, notes, and snippets.

Keybase proof

I hereby claim:

To claim this, I am signing this object:

@AOrobator
AOrobator / OkHttp.kt
Created July 21, 2018 17:21
OkHttpExtensions
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import org.amshove.kluent.`should equal`
/**
* OkHttp3 extensions for syntactic sugar while testing
*/
enum class HttpMethod {
DELETE,
GET,
fun realmTransactionSync(transaction: (Realm) -> Unit) {
val realm = Realm.getDefaultInstance()
var canceled = false
realm.beginTransaction()
try {
transaction(realm)
} catch (e: Exception) {
e.printStackTrace()
realm.cancelTransaction()
override fun scanSongIntoLibrary(filePath: String): SongId {
var newSongId: SongId = InvalidSongId
realmTransaction {
if (getSongForFilepath(it, filePath) == null) {
val song = Song {
id = Database.getNextId(it, Song::class.java)
newSongId = // get next ValidSongId
// Initialize title, artist, and album for the song
}
it.copyToRealm(song)
@AOrobator
AOrobator / RealmAction.kt
Created April 7, 2018 19:32
RealmTransaction
fun realmTransaction(onError: (Throwable) -> Unit = {}, transaction: (Realm) -> Unit) {
val realm = Realm.getDefaultInstance()
try {
realm.executeTransactionAsync { transaction(it) }
} catch (e: Exception) {
onError(e)
}
realm.close()
class RealmSongRepository : SongRepository {
override fun addSongToLibrary(filePath: String): Single<SongId> {
return Single.fromCallable {
scanSongIntoLibrary(filePath)
}
.subscribeOn(io())
.observeOn(mainThread())
}
override fun scanSongIntoLibrary(filePath: String): SongId {
@AOrobator
AOrobator / FolderBrowsingPresenterTest.kt
Created April 7, 2018 17:00
Tests don't cover all bugs
@Test
fun `When unscanned song clicked, song is scanned into library`() {
val presenter = FolderBrowsingPresenter(queue, MockSongRepository())
val target: FolderBrowsingPresenter.Target = mock()
presenter.attach(target)
presenter.onUnscannedSongClicked(
DirectoryItemSong(
name = "01 Get You.m4a",
lastModifiedTime = 1234L,
@AOrobator
AOrobator / FolderBrowsingPresenter.kt
Created April 7, 2018 16:21
OnUnscannedSongClicked
fun onUnscannedSongClicked(song: DirectoryItemSong) {
val songFile = File(song.path)
if (songFile.extension in supportedFormats) {
target?.showLoading()
songRepo
.addSongToLibrary(song.path)
.subscribe {
target?.hideLoading()
target?.playSong(it)
}
sealed class SongId
data class ValidSongId(id: Long) : SongId()
object InvalidSongId : SongId()
val Song.typedId: SongId = if (this.id == -1L) InvalidSongId else SongId(this.id)
class RealmSongRepository: SongRepository {
override fun getSongById(songId: SongId) : Song? = when (songId) {
is ValidSongId -> getSongFromRealm(songId.id) // smart cast to ValidSongId
InvalidSongId -> null
// No else statement required because the compiler knows we’ve covered all cases
}
}