Skip to content

Instantly share code, notes, and snippets.

View marcellogalhardo's full-sized avatar
🇧🇷
Gradle is building...

Marcello Galhardo marcellogalhardo

🇧🇷
Gradle is building...
View GitHub Profile
@marcellogalhardo
marcellogalhardo / KotlinResult.kt
Last active April 9, 2021 07:45
A Result class with Public API compatible to kotlin.Result for a easy migration
import java.io.Serializable
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/**
* A discriminated union that encapsulates a successful outcome with a value of type [T]
* or a failure with an arbitrary [Throwable] exception.
*/
public sealed class Result<out T> : Serializable {
@marcellogalhardo
marcellogalhardo / Option.kt
Created November 23, 2020 12:23
An option class for Kotlin.
import java.io.Serializable
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/**
* A type that represents either a wrapped value or null, the absence of a value.
*/
public sealed class Option<out T> : Serializable {
@marcellogalhardo
marcellogalhardo / SavedStateHandle+StateFlow.kt
Last active July 23, 2023 23:46
A helper function to let you expose a MutableStateFlow from a SavedStateHandle.
/**
* Returns a [StateFlow] that access data associated with the given key.
*
* @param scope The scope used to synchronize the [StateFlow] and [SavedStateHandle]
* @param key The identifier for the value
* @param initialValue If no value exists with the given [key], a new one is created
* with the given [initialValue].
*
* @see SavedStateHandle.getLiveData
*/
@marcellogalhardo
marcellogalhardo / ViewScenario.kt
Last active February 5, 2021 08:37
A simple scenario to run test against a view in a isolated fragment container.
/**
* Launches a [View] in an [ViewHostFragment] root view container (onCreateView).
* [ViewHostFragment] is hosted by an empty [FragmentActivity] which will [instantiate]
* the [Fragment] and waits for it to reach a resumed state.
*
* If your testing [View] has a dependency to specific theme such as [R.style.Theme_AppCompat],
* use the theme ID parameter in [launchViewInFragment] method.
*
* Usage example:
*
@marcellogalhardo
marcellogalhardo / CoroutineRule.kt
Last active July 7, 2021 12:06
A test rule to allow testing coroutines with ease. It provides you a `scope: TestCoroutineScope` and `dispatcher: TestCoroutineDispatcher` ready to be used.
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
@Suppress("MemberVisibilityCanBePrivate")
class CoroutineRule(
@marcellogalhardo
marcellogalhardo / ViewViewModel.kt
Created February 12, 2021 09:16
A small sample of ViewModel for Views. Not production ready. :D
inline fun <reified VM : ViewModel> View.getViewModel(): VM {
check(isAttachedToWindow) { "ViewModel can be accessed only when View is attached." }
val lifecycleOwner = lifecycleOwner
check(lifecycleOwner is ViewModelStoreOwner)
check(lifecycleOwner is HasDefaultViewModelProviderFactory)
return ViewModelProvider(lifecycleOwner, lifecycleOwner.defaultViewModelProviderFactory)
.get(id.toString(), VM::class.java)
}
@PublishedApi
internal val View.lifecycleOwner: LifecycleOwner
@marcellogalhardo
marcellogalhardo / Example.kt
Created February 12, 2021 13:28
A simple SystemServiceLocator that enables to easy customization of Context `getSystemService`.
class MainApplication : Application() {
private val component = MainComponent.Factory.create(application = this)
private val locator = SystemServiceLocator {
register { component.getFragmentFactory() }
}
override fun getSystemService(name: String): Any? {
return locator.getSystemService(name) ?: super.getSystemService(name)
@marcellogalhardo
marcellogalhardo / AssistedViewModel.kt
Last active August 6, 2021 13:47
A ViewModel that supports assisted injection.
package dev.marcellogalhardo.viewmodel
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.AbstractSavedStateViewModelFactory
@marcellogalhardo
marcellogalhardo / build.gradle.kts
Created May 25, 2021 09:18
Root gradle.build.kts global settings for KAPT
allprojects {
afterEvaluate {
// Global KAPT flags applied to all projects.
extensions.findByType<KaptExtension>()?.apply {
// Do not replace unknown types (including types for the generated classes) by NonExistentClass.
correctErrorTypes = true
// Provide links to locations in the original Kotlin code rather than generated Java stubs
// as it reports errors encountered during annotation processing.
@marcellogalhardo
marcellogalhardo / SingleFragmentActivity.kt
Created June 1, 2021 16:05
A default AppCompatActivity that hosts a Fragment.
import android.content.Intent
import android.os.Bundle
import androidx.annotation.CallSuper
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentContainerView
import androidx.fragment.app.commitNow
import com.deliveryhero.commons.mvvm.R
import kotlin.reflect.KClass