Skip to content

Instantly share code, notes, and snippets.

@Grohden
Last active December 7, 2018 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Grohden/242da5d7ae7bf8aa3a34d6afcf7789fa to your computer and use it in GitHub Desktop.
Save Grohden/242da5d7ae7bf8aa3a34d6afcf7789fa to your computer and use it in GitHub Desktop.
A lazy way to execute a map on a collection
import java.lang.ref.WeakReference
// It doesn't matter for the receiver which one is the received argument
typealias LateBoxList<R> = List<LateMapBox<*, R>>
fun <T, R> Iterable<T>.mapAsLateBox(mapper: (T) -> R): List<LateMapBox<T, R>> {
return this.map { LateMapBox(it, mapper) }
}
/**
* This class is intended to be used along with realm
* on situations that you need to map something in a more complex
* way (like querying another objects) only when the object is actually
* required. Also, this is supposed to take less memory
*
* @param originalObject the original object reference
* @param mapper The mapper function
*
* Note: you have to be careful about what you put in the mapper function,
* as it will create a strong reference for referenced objects.
*
*/
class LateMapBox<T, R>(
private val originalObject: T,
private val mapper: (T) -> R
) {
private var ref: WeakReference<R>? = null
/**
* Returns the mapped object, caching it's reference
*
* @return the mapped object
*/
fun get(): R {
return ref?.get() ?: mapper(originalObject).also {
ref = WeakReference(it)
}
}
/**
* Returns the mapped object if possible
*
* @return the mapped object
*/
fun tryGet(): R? {
return try {
get()
} catch (t: Throwable) {
Log.e(LateMapBox::class.java.simpleName, "Error getting object", t)
null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment