Last active
March 10, 2022 16:07
-
-
Save gabriel-TheCode/49e24211cd0e5d82726ff5a4a3a36b13 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@ExperimentalCoroutinesApi | |
@AndroidEntryPoint | |
class MainActivity : AppCompatActivity(), BlogAdapter.BlogItemListener { | |
private val viewModel: MainViewModel by viewModels() | |
private lateinit var adapter: BlogAdapter | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
setupRecyclerView() | |
subscribeObservers() | |
viewModel.setStateEvent(MainStateEvent.GetBlogEvents) | |
swipeRefreshLayout.setOnRefreshListener { | |
viewModel.setStateEvent(MainStateEvent.GetBlogEvents) | |
} | |
} | |
private fun subscribeObservers() { | |
viewModel.dataState.observe(this, Observer { dataState -> | |
when (dataState) { | |
is DataState.Success<List<Blog>> -> { | |
displayLoading(false) | |
populateRecyclerView(dataState.data) | |
} | |
is DataState.Loading -> { | |
displayLoading(true) | |
} | |
is DataState.Error -> { | |
displayLoading(false) | |
displayError(dataState.exception.message) | |
} | |
} | |
}) | |
} | |
private fun displayError(message: String?) { | |
if (message.isNotBlank()) { | |
Toast.makeText(this, message, Toast.LENGTH_LONG).show() | |
} else { | |
Toast.makeText(this, "Unknown error", Toast.LENGTH_LONG).show() | |
} | |
} | |
private fun displayLoading(isLoading: Boolean) { | |
swipeRefreshLayout.isRefreshing = isLoading | |
} | |
private fun populateRecyclerView(blogs: List<Blog>) { | |
if (blogs.isNotEmpty()) adapter.setItems(ArrayList(blogs)) | |
} | |
private fun setupRecyclerView() { | |
adapter = BlogAdapter(this) | |
blog_recyclerview.layoutManager = LinearLayoutManager(this) | |
blog_recyclerview.adapter = adapter | |
} | |
override fun onClickedBlog(blogTitle: CharSequence) { | |
Toast.makeText(this, blogTitle, Toast.LENGTH_SHORT).show() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment