Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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