Skip to content

Instantly share code, notes, and snippets.

Avatar
🍃

Takao Chiba chibatching

🍃
View GitHub Profile
@chibatching
chibatching / PagedListGroup.java
Last active Feb 27, 2020
Use PagedList with Groupie
View PagedListGroup.java
import android.arch.paging.AsyncPagedListDiffer;
import android.arch.paging.PagedList;
import android.support.annotation.NonNull;
import android.support.v7.recyclerview.extensions.AsyncDifferConfig;
import android.support.v7.util.DiffUtil;
import android.support.v7.util.ListUpdateCallback;
import com.xwray.groupie.Group;
import com.xwray.groupie.GroupDataObserver;
import com.xwray.groupie.Item;
View SampleViewModel.kt
class SampleViewModel : ViewModel() {
val sampleData = UiAsyncLoadLiveData<String> {
value = try {
async(coroutineContext + CommonPool) {
"very long time process!"
}.await()
} catch (e: CancellationException) {
null
}
}
@chibatching
chibatching / FlowableLiveData.kt
Last active Apr 19, 2019
LiveData as Flow of Kotlin Coroutines
View FlowableLiveData.kt
fun <T> LiveData<T>.asFlow() = flowViaChannel<T?> {
it.send(value)
val observer = Observer<T> { t -> it.offer(t) }
observeForever(observer)
it.invokeOnClose {
removeObserver(observer)
}
}
val text = MutableLiveData<String>()
@chibatching
chibatching / FlowThrottleDebounce.kt
Last active Mar 15, 2022
Throttle and Debounce on Flow Kotlin Coroutines
View FlowThrottleDebounce.kt
fun <T> Flow<T>.throttle(waitMillis: Int) = flow {
coroutineScope {
val context = coroutineContext
var nextMillis = 0L
var delayPost: Deferred<Unit>? = null
collect {
val current = SystemClock.uptimeMillis()
if (nextMillis < current) {
nextMillis = current + waitMillis
@chibatching
chibatching / SomeFragment.kt
Last active Dec 5, 2019
Simple ViewModel Dagger Injection
View SomeFragment.kt
import androidx.fragment.app.viewModels
import dagger.android.support.DaggerFragment
class SomeFragment : DaggerFragment() {
@Inject
lateinit var viewModelFactory: ViewModelFactory<SomeViewModel>
private val viewModel: SomeViewModel by viewModels { viewModelFactory }
@chibatching
chibatching / SaveAllValueToSP.kt
Last active Jan 21, 2020
Save all values include default values declared in KotprefModel
View SaveAllValueToSP.kt
SomePref::class.declaredMemberProperties
.forEach { property ->
property.isAccessible = true
(property.getDelegate(SomePref) as? AbstractPref<Any>)?.let {
it.setToPreference(property, property.get(SomePref)!!, SomePref.preferences)
println("save preference ${property.name} -> ${property.get(SomePref)}")
}
(property.getDelegate(SomePref) as? AbstractStringSetPref)?.let {
getSharedPreferences(SomePref.kotprefName, Context.MODE_PRIVATE)
.edit()