Upgrade to Pro — share decks privately, control downloads, hide ads and more …

An Android Dev start to Kotlin MPP

An Android Dev start to Kotlin MPP

Roberto Orgiu

November 16, 2020
Tweet

More Decks by Roberto Orgiu

Other Decks in Programming

Transcript

  1. Premises I want to reuse my knowledge I am an

    Android Dev I don’t want to be x-plat
  2. @Serializable data class DayLight( val image: String, val color: String,

    val reason: String, val date: String ) @Serializable data class Lights( val todayColor: String, val picture: String, val calendar: List<DayLight> ) :shared
  3. class LightRepository { private val httpClient = HttpClient { install(JsonFeature)

    { val json = Json { ignoreUnknownKeys = true } serializer = KotlinxSerializer(json) } } suspend fun getLights() : Lights = httpClient.get(LIGHTS_ENDPOINT) } :shared
  4. :android class LightsViewModel : ViewModel() { private val repository by

    lazy { LightRepository() } private val _state : MutableLiveData<Lce<Lights>> = MutableLiveData() val state : LiveData<Lce<Lights>> get() = _state fun loadLights() { _state.postValue(Lce.Loading) viewModelScope.launch { try { val lights = repository.getLights() _state.postValue(Lce.Success(lights)) } catch(e: Exception) { _state.postValue(Lce.Error(e)) } } } }
  5. val state : LiveData<Lce<Lights>> get() = _state fun loadLights() {

    _state.postValue(Lce.Loading) viewModelScope.launch { try { val lights = repository.getLights() _state.postValue(Lce.Success(lights)) } catch(e: Exception) { _state.postValue(Lce.Error(e)) } }
  6. Delete all .iml files in the project Close project and

    IDE Delete .idea directory Re-import the project
  7. extension ContentView { enum LoadableLights { case loading case result(Lights)

    case error(String) } class ViewModel: ObservableObject { let repo : LightRepository @Published var lights = LoadableLights.loading init(repo: LightRepository){ self.repo = repo self.loadLights() } func loadLights() { self.lights = .loading repo.getLights(completionHandler: { lights, error in if let lights = lights { self.lights = .result(lights) } else { self.lights = .error(error?.localizedDescription ?? "error") } }) } } }
  8. self.repo = repo self.loadLights() } func loadLights() { self.lights =

    .loading repo.getLights(completionHandler: { lights, error in if let lights = lights { self.lights = .result(lights) } else { self.lights = .error(error?.localizedDescription ?? "e } }) }
  9. private func listView() -> AnyView { switch viewModel.lights { case

    .loading: return AnyView(Text("Loading...").multilineTextAlignment(.center)) case .result(let lodableLights): return AnyView(LightsView(lights: lodableLights)) case .error(let description): return AnyView(Text(description).multilineTextAlignment(.center)) } }
  10. Q&A