Skip to content

Instantly share code, notes, and snippets.

@aleweichandt
Created August 16, 2021 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleweichandt/0fa599209521712266e20f902a4c78ed to your computer and use it in GitHub Desktop.
Save aleweichandt/0fa599209521712266e20f902a4c78ed to your computer and use it in GitHub Desktop.
Force refresh implementation
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/todo_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="@layout/list_item_todo" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
@AndroidEntryPoint
class TodoListFragment : StackFragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
bindings = FragmentTodoListBinding.inflate(inflater, container, false)
bindings.viewModel = viewModel
bindings.lifecycleOwner = viewLifecycleOwner
bindings.todoList.adapter = adapter
// Attach refresh listener
with(bindings.swipeRefresh) {
setOnRefreshListener(viewModel)
}
return bindings.root
}
private fun observeViewModel() {
viewModel.todos.observe(viewLifecycleOwner) {
adapter.submitList(it)
}
// Enable loading spinner
viewModel.refreshing.observe(viewLifecycleOwner) {
bindings.swipeRefresh.isRefreshing = it
}
}
}
@HiltViewModel
class TodoListViewModel(
private val getAllTodosUseCase: GetAllTodosUseCase
) : ViewModel(), SwipeRefreshLayout.OnRefreshListener {
private val _todos = MutableLiveData<List<Todo>>()
val todos: LiveData<List<Todo>>
get() = _todos
private val _refreshing = MutableLiveData<Boolean>(false)
val refreshing: LiveData<Boolean>
get() = _refreshing
// initial fetch triggered onViewCreated
fun onViewCreated() {
refresh()
}
// pull to refresh provided by SwipeRefreshLayout.OnRefreshListener
override fun onRefresh() {
refresh(true)
}
private fun refresh(force: Boolean = false) {
viewModelScope.launch {
getAllTodosUseCase(force)
.onStart { _refreshing.value = true }
.onCompletion { _refreshing.value = false }
.collect { response ->
when (response) {
is Result.Success -> _todos.value = response.result
else -> Unit //TODO handle error
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment