Sajjad_

Kotlin Extension function usage

Feb 5th, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.82 KB | None | 0 0
  1. class MainActivity : AppCompatActivity() {
  2.  
  3.     private val adapter = ChartsAdapter()
  4.  
  5.     private lateinit var model: MainModel
  6.  
  7.     override fun onCreate(savedInstanceState: Bundle?) {
  8.         super.onCreate(savedInstanceState)
  9.         setContentView(R.layout.activity_main)
  10.         setSupportActionBar(toolbar)
  11.         drawer?.run {
  12.             val toggle = ActionBarDrawerToggle(
  13.                     this@MainActivity,
  14.                     drawer,
  15.                     toolbar,
  16.                     R.string.navigation_drawer_open,
  17.                     R.string.navigation_drawer_close
  18.             )
  19.             addDrawerListener(toggle)
  20.             toggle.syncState()
  21.         }
  22.         navigation.setNavigationItemSelectedListener {
  23.             model.action(SelectCity(it.title.toString()))
  24.         }
  25.         recycler.adapter = adapter
  26.         initModel()
  27.     }
  28.  
  29.     private fun initModel() {
  30.         model = ViewModelProviders.of(this).get(MainModel::class.java)
  31.         model.loading.observe { displayLoading(it == true) }
  32.         model.city.observe { displayCity(it ?: "") }
  33.         model.charts.observe { displayCharts(it ?: emptyList()) }
  34.         model.message.observe { displayMessage(it ?: "") }
  35.     }
  36.  
  37.     private fun displayLoading(loading: Boolean) {
  38.         progress.visibility = if (loading) VISIBLE else INVISIBLE
  39.     }
  40.  
  41.     private fun displayCity(city: String) {
  42.         title = city
  43.         for (item in navigation.menu)
  44.             item.isChecked = item.title == city
  45.     }
  46.  
  47.     private fun displayCharts(charts: List<Chart>) { adapter.charts = charts }
  48.  
  49.     private fun displayMessage(message: String) {
  50.         if (message.isNotBlank()) toast(message)
  51.     }
  52.  
  53.     private fun <T> LiveData<T>.observe(observe: (T?) -> Unit)
  54.             = observe(this@MainActivity, Observer { observe(it) })
  55. }
Advertisement
Add Comment
Please, Sign In to add comment