Last active
December 7, 2018 14:58
-
-
Save Grohden/242da5d7ae7bf8aa3a34d6afcf7789fa to your computer and use it in GitHub Desktop.
A lazy way to execute a map on a collection
This file contains hidden or 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 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