Skip to content

Instantly share code, notes, and snippets.

Avatar
🏠
Working from home

Patryk Kosieradzki k0siara

🏠
Working from home
View GitHub Profile
View CollectingFlowExample.kt
// ViewModel with some Flows to observe and collect
abstract class BaseViewModel<STATE, EVENT : UiEvent, EFFECT : UiEffect>(
initialState: UiState<STATE> = UiState.Loading
) : ViewModel() {
...
private val _uiState: MutableStateFlow<UiState<STATE>> = MutableStateFlow(initialState)
val uiState = _uiState.asStateFlow()
View FlowObserver.kt
class FlowObserver<T>(
lifecycleOwner: LifecycleOwner,
private val flow: Flow<T>,
private val collector: suspend (T) -> Unit
) {
private var job: Job? = null
init {
lifecycleOwner.lifecycle.addObserver(
View CustomListAdapter.kt
class CustomAdapter : ListAdapter<Item, ItemViewHolder>(DiffUtilCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SpotViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item, parent, false)
return ItemViewHolder(view)
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
holder.bind(currentList[position])
}
View RenderItems.kt
fun renderItems(newItems: List){
val diffResult: DiffUtil.DiffResult = DiffUtil.calculateDiff(DiffUtilCallback(oldItems, newItems))
diffResult.dispatchUpdatesTo(this) // this : RecyclerView.Adapter
}
View DiffUtilCallback.kt
class DiffUtilCallback(
private val oldItems: List,
private val newItems: List
) : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldItems[oldItemPosition].id == newItems[newItemPosition].id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
View GetItemCount.kt
@Override
public int getItemCount() {
if (dataset == null)
return 0;
return dataset.size();
}
View OnBindViewHolder.kt
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is CustomViewHolder) {
// bind data to the views of CustomViewHolder
}
...
}
@k0siara
k0siara / OnCreateViewHolder.kt
Created May 30, 2021
OnCreateViewHolder.kt
View OnCreateViewHolder.kt
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
// return new ViewHolder reference here based on the viewType
}
View build.gradle
def appId = "com.patrykkosieradzki.moviebox"
android {
...
defaultConfig {
...
applicationId appId
}
}
View build.gradle
android {
testOptions {
...
animationsDisabled = true
}
}