Skip to content

Instantly share code, notes, and snippets.

@hansenji
hansenji / FlowLifecycleExt.kt
Created December 31, 2020 19:18
Collect flows tied to the Lifecycle
class LifecycleGroup(val lifecycleOwner: LifecycleOwner) {
/**
* Recommended for the majority of use cases
* The crucial difference from [collect] is that when the original flow emits a new value, [block] for previous
* value is cancelled.
**/
inline fun <T> Flow<T>.collectLatestWhenStarted(crossinline block: suspend (T) -> Unit): Job {
return lifecycleOwner.lifecycleScope.launchWhenStarted {
this@collectLatestWhenStarted.collectLatest {
block(it)
@hansenji
hansenji / ViewCoroutineScope
Created December 9, 2020 23:03
Coroutine Scope for a view.
import android.view.View
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import kotlin.coroutines.CoroutineContext
internal val View.viewScope: ViewCoroutineScope
get() {
val scope = getTag(R.id.coroutineScope) as ViewCoroutineScope?
class MyViewModel
@ViewModelInject constructor(
Long foo, @Assisted SavedStateHandle savedStateHandle
): ViewModel() {
//...
}
@ViewModelModule
@Module(includes = ViewModelInject_VMModule::class)
abstract class VMModule {}
@hansenji
hansenji / savedstate_boilerplate.kt
Last active April 1, 2019 03:46
savedstate_boilerplate.kt
@AssistedInject.Factory
interface Factory : ViewModelAssistedFactory<MyViewModel>
@Module
abstract class DetailModule {
@Binds
@IntoMap
@ViewModelKey(MyViewModel.class)
abstract fun bindFactory(factory: MyViewModel.Factory): ViewModelAssistedFactory
}
@hansenji
hansenji / JacksonKotlinModuleExample.kt
Created April 4, 2017 19:43
Jackson Kotlin Module Example
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
fun main(args: Array<String>) {
// val mapper = ObjectMapper().registerModule(KotlinModule())
// val mapper = ObjectMapper().registerKotlinModule()
val mapper = jacksonObjectMapper()
val writer = mapper.writerWithDefaultPrettyPrinter()
val json1 = writer.writeValueAsString(Data1(1, "Foo", "Bar"))