Created
September 10, 2020 01:58
-
-
Save carolinemusyoka/61c1bef37b925fecee6773c2a0907b19 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class MainActivity : AppCompatActivity() { | |
private lateinit var viewModel: MainViewModel | |
private lateinit var adapter: MainAdapter | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
setupViewModel() | |
setupUI() | |
setupObservers() | |
} | |
private fun setupViewModel() { | |
viewModel = ViewModelProviders.of( | |
this, | |
ViewModelFactory(ApiHelper(RetrofitBuilder.apiService)) | |
).get(MainViewModel::class.java) | |
} | |
private fun setupUI() { | |
superhero_recycler.addItemDecoration(DefaultItemDecorator(4, 6)) | |
superhero_recycler.apply { | |
setHasFixedSize(true) | |
layoutManager = GridLayoutManager(this@MainActivity,2) | |
} | |
adapter = MainAdapter(arrayListOf()) | |
superhero_recycler.adapter = adapter | |
} | |
private fun setupObservers() { | |
viewModel.getSuperHeroes().observe(this, { | |
it?.let { resource -> | |
when (resource.status) { | |
Status.SUCCESS -> { | |
superhero_recycler.visibility = View.VISIBLE | |
progressBar.visibility = View.GONE | |
resource.data?.let { heroResponse | |
-> retrieveList(heroResponse) } | |
} | |
Status.ERROR -> { | |
superhero_recycler.visibility = View.VISIBLE | |
progressBar.visibility = View.GONE | |
Toast.makeText(this, it.message, Toast.LENGTH_LONG).show() | |
} | |
Status.LOADING -> { | |
progressBar.visibility = View.VISIBLE | |
superhero_recycler.visibility = View.GONE | |
} | |
} | |
} | |
}) | |
} | |
private fun retrieveList(hero: List<Hero>) { | |
adapter.apply { | |
addSuperHeroes(hero) | |
notifyDataSetChanged() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment