Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

View mrmitew's full-sized avatar

Stefan Mitev mrmitew

View GitHub Profile
@mrmitew
mrmitew / RxWriteByteStreamToFile.kt
Last active September 21, 2018 10:56
Extension function for RxJava's Flowable for writing bytes from a stream into a file
/**
* Extension function for RxJava's Flowable for writing bytes from a stream into a file
* The [FileOutputStream] will be automatically flushed and then closed when the flowable
* terminates or is disposed.
*
* Example usage:
*
* getAudioStream()
* .observeOn(AndroidSchedulers.mainThread())
* .subscribeOn(Schedulers.computation())
@mrmitew
mrmitew / SuspendClassInitializerExample.kt
Last active September 12, 2018 14:27
Using kotlin's features to inject values that are suspend computed into any class constructor
import android.os.Looper
import kotlinx.coroutines.experimental.*
import kotlin.system.measureTimeMillis
abstract class SuspendClassInitializer<out T> constructor(
private val initDispatcher: CoroutineDispatcher,
instanceFactory: () -> T
) {
private val delegate = lazy(instanceFactory)
@mrmitew
mrmitew / ViewPagerPager.kt
Created September 5, 2018 14:15
Helper class for automatically scrolling pages of a [ViewPager] which does not allow you to customize the speed at which it changes page when directly setting the current page.
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@mrmitew
mrmitew / View.kt
Created August 5, 2018 19:31
Set a click listener on a view, backed up by an actor that discards all clicks until the suspending action returns
/**
* Set a click listener on a view and back it up by an actor that allows
* execution of a single action block at a time. Subsequent requests will be discarded until action returns.
*/
fun View.setOnRendezvousClickListener(action: suspend (View) -> Unit) {
val eventActor = actor<View>(UI, capacity = 0) {
for (event in channel) action(event)
}
setOnClickListener {
@mrmitew
mrmitew / ClosedRange.kt
Created August 5, 2018 19:29
Get a random number that is in a given closed range
fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start
/**
* Makes the height match the width, using the set ratio
*/
class RatioImageView : ImageView {
private var ratio = 1f
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
@mrmitew
mrmitew / NetServiceExt.swift
Created August 1, 2018 18:43
Extension functions for NetService and NSData that provide an easy way to get IPV4 as String from any resolved NetService
// Example usage can be found in the following repository: https://github.com/mrmitew/Bonjour-iOS
extension NetService {
func getIpV4() -> String? {
if let ipData = self.addresses?.first {
return (ipData as NSData).getIpV4()
}
return nil
}
}
fun main(args: Array<String>) {
if (args[0] == "start") {
launch(CommonPool) {
println("Launching")
SerialisationHelper.test()
println("Finished")
}
}
@mrmitew
mrmitew / InFlightJobCache.kt
Created April 30, 2018 15:49
In-flight job caching with cancellation support
class InFlightJobCache<T> {
private val jobs = mutableMapOf<String, Deferred<T>>()
private val mux = Mutex()
suspend fun getOrFetch(key: String, factory: suspend () -> T): Deferred<T> = mux.withLock {
val request = jobs.getOrDefault(key, async(start = CoroutineStart.LAZY) { factory() })
jobs[key] = request
return request
}
@mrmitew
mrmitew / ReactiveCache.kt
Created October 6, 2017 10:44
Caching of observables for inflight requests
class ReactiveCache<in K, V>(private val generator: Function<K, Observable<V>>) {
private val requests: MutableMap<K, ConnectableObservable<V>> = HashMap()
@Throws(Exception::class)
operator fun get(key: K): Observable<V> {
var result: ConnectableObservable<V> = Observable.empty<V>().replay()
synchronized(requests) {
val current = requests[key]
if (current != null) {
return current