Skip to content

Instantly share code, notes, and snippets.

@oscargrgm
oscargrgm / ActivityExt.kt
Last active February 25, 2021 11:24
Useful Activity's extension functions.
inline fun <reified T : Activity> Activity.launchActivity(extras: Bundle? = null) {
val intent = Intent(this, T::class.java).apply {
extras?.let { putExtras(it) }
}
startActivity(intent)
}
inline fun <reified T : Any> Activity.extra(key: String, default: T) = lazy {
val value = intent?.extras?.get(key)
if (value is T) value else default
@oscargrgm
oscargrgm / Mapper.kt
Last active June 30, 2021 11:06
Mapper to convert network data into domain model and viceversa.
interface Mapper<D, M> {
fun toModel(data: D): M
fun toData(model: M): D
}
object ModelMapper : Mapper<Data, Model> {
override fun toModel(data: Data): Model = with(data) {
Model(...)
}
@oscargrgm
oscargrgm / AppNavigationTest.kt
Last active February 26, 2021 17:30
Useful testing code from Udacity's Android Kotlin Developer Nanodegree.
/**
* Extension function to obtain the content description for the navigation icon.
*/
fun <T : Activity> ActivityScenario<T>.getToolbarNavigationContentDescription(): String {
var description = ""
onActivity {
description =
it.findViewById<Toolbar>(R.id.toolbar).navigationContentDescription as String
}
return description
@oscargrgm
oscargrgm / ModelConverter.kt
Created July 16, 2021 08:06
Deserialize any String into an object using Gson.
private inline fun <reified T> String.asModel(): T = Gson().fromJson(this, T::class.java)
// val result: String = ...
// val model = result.asModel<AnyModel>()