Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce kotlin coroutines flow #21

Merged
merged 8 commits into from
Oct 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions androidApp/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ android {
}

lintOptions {
setAbortOnError(false)
isAbortOnError = false
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
Expand All @@ -46,15 +46,18 @@ dependencies {
implementation(kotlin("stdlib-jdk7", KotlinCompilerVersion.VERSION))
implementation(project(":shared"))

implementation("androidx.constraintlayout:constraintlayout:2.0.0-beta1")
implementation("androidx.appcompat:appcompat:1.0.2")
implementation("androidx.constraintlayout:constraintlayout:2.0.0-beta2")
implementation("androidx.appcompat:appcompat:1.1.0")
implementation("androidx.recyclerview:recyclerview:1.0.0")
implementation("androidx.lifecycle:lifecycle-runtime:2.0.0")
implementation("androidx.lifecycle:lifecycle-extensions:2.0.0")
implementation("androidx.lifecycle:lifecycle-runtime:2.1.0")
implementation("androidx.lifecycle:lifecycle-extensions:2.1.0")
implementation("com.github.pedrovgs:renderers:3.4.0")
implementation("com.squareup.okhttp3:okhttp:3.11.0")
implementation("com.squareup.okhttp3:okhttp:3.12.1")
implementation("com.squareup.picasso:picasso:2.71828")

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.1")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.1")

testImplementation("junit:junit:4.12")
androidTestImplementation("org.mockito:mockito-android:2.28.2")
androidTestImplementation("com.nhaarman.mockitokotlin2:mockito-kotlin:2.1.0")
Expand Down
23 changes: 16 additions & 7 deletions androidApp/src/main/kotlin/com/karumi/gallery/app/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,29 @@ class MainActivity : AppCompatActivity(), PhotoListPresenter.View {
presenter.detachView()
}

override fun showLoader() {
progress.visibility = View.VISIBLE
override fun render(state: PhotoListPresenter.View.State) {
when (state) {
is PhotoListPresenter.View.State.Loading -> renderLoading()
is PhotoListPresenter.View.State.Error -> renderError()
is PhotoListPresenter.View.State.Success -> renderPhotos(state.photos)
}
}

override fun hideLoader() {
progress.visibility = View.GONE
private fun renderLoading() {
progress.visibility = View.VISIBLE
errorInformation.visibility = View.GONE
}

override fun onLoadError() {
private fun renderError() {
progress.visibility = View.GONE
errorInformation.visibility = View.VISIBLE
}

override fun plusAssign(shots: List<PhotoShot>) {
val items = shots.map { PhotoItem(it.id, it.thumbnailUrl, it.authorName) }
private fun renderPhotos(photos: List<PhotoShot>) {
progress.visibility = View.GONE
errorInformation.visibility = View.GONE

val items = photos.map { PhotoItem(it.id, it.thumbnailUrl, it.authorName) }
adapter.addAll(items)
adapter.notifyDataSetChanged()
}
Expand Down
10 changes: 5 additions & 5 deletions iosApp/PhotoGallery/PhotoCollectionViewCell.xib
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14490.49"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="PhotoCollectionViewCellReuseIdentifier" id="Kvj-ya-9xL" customClass="PhotoCollectionViewCell" customModule="Dribbble_app" customModuleProvider="target">
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="PhotoCollectionViewCellReuseIdentifier" id="Kvj-ya-9xL" customClass="PhotoCollectionViewCell" customModule="PhotoGallery" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="220" height="204"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" insetsLayoutMarginsFromSafeArea="NO">
<rect key="frame" x="0.0" y="0.0" width="220" height="204"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="eiD-pr-Gu4">
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="eiD-pr-Gu4">
<rect key="frame" x="0.0" y="0.0" width="220" height="188"/>
</imageView>
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="RoS-jn-q9a">
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="RoS-jn-q9a">
<rect key="frame" x="0.0" y="0.0" width="220" height="188"/>
</imageView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="by Nick Slater" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="gqP-3L-qtE">
Expand Down
32 changes: 21 additions & 11 deletions iosApp/PhotoGallery/PhotoListViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,34 @@ class PhotoListViewController: UIViewController, PhotoListPresenterView {
errorTextLabel.isHidden = true
}

func plusAssign(shots: [PhotoShot]) {
let newItems = shots.map(PhotoListItem.init)
items.append(contentsOf: newItems)
allItemsCollectionView.reloadData()
func render(state: PhotoListPresenterViewState) {
if state is PhotoListPresenterViewState.Loading {
renderLoading()
} else if state is PhotoListPresenterViewState.Error {
renderError()
} else if let state = state as? PhotoListPresenterViewState.Success {
render(photos: state.photos)
}
}
func showLoader() {

func renderLoading() {
loadingIndicator.startAnimating()
errorTextLabel.isHidden = true
}

func hideLoader() {
loadingIndicator.stopAnimating()
func renderError() {
loadingIndicator.isHidden = true
}

func onLoadError() {
errorTextLabel.isHidden = false
}

func render(photos: [PhotoShot]) {
loadingIndicator.isHidden = true
errorTextLabel.isHidden = true

let newItems = photos.map(PhotoListItem.init)
items.append(contentsOf: newItems)
allItemsCollectionView.reloadData()
}
}

extension PhotoListViewController: UICollectionViewDelegateFlowLayout {
Expand Down
25 changes: 15 additions & 10 deletions shared/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ group 'com.karumi'
version '0.0.1'

apply plugin: "kotlin-multiplatform"
apply plugin: 'com.android.library'
apply plugin: "kotlinx-serialization"
apply plugin: 'com.android.library'
apply plugin: "io.gitlab.arturbosch.detekt"
apply plugin: "org.jlleitschuh.gradle.ktlint"

Expand All @@ -31,52 +31,56 @@ kotlin {
all {
languageSettings {
useExperimentalAnnotation('kotlin.Experimental')
useExperimentalAnnotation('kotlin.time.ExperimentalTime')
useExperimentalAnnotation('kotlinx.coroutines.FlowPreview')
useExperimentalAnnotation('kotlinx.coroutines.ExperimentalCoroutinesApi')
}
}
commonMain {
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlin_version"
implementation 'org.jetbrains.kotlin:kotlin-stdlib'

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-common:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serialization_version"

implementation "io.ktor:ktor-client-core:$ktor_version"
implementation "io.ktor:ktor-client-json:$ktor_version"
implementation "io.ktor:ktor-client-logging:$ktor_version"
implementation "io.ktor:ktor-client-serialization:$ktor_version"
}
}
commonTest {
dependencies {
implementation "org.jetbrains.kotlin:kotlin-test-common:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-test-annotations-common:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-common:$coroutines_version"

//implementation "io.ktor:ktor-client-mock-native:$ktor_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"

api "io.ktor:ktor-client-mock:$ktor_version"
}
}
androidMain {
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serialization_version"

implementation "io.ktor:ktor-client-android:$ktor_version"
implementation "io.ktor:ktor-client-core-jvm:$ktor_version"
implementation "io.ktor:ktor-client-json-jvm:$ktor_version"
implementation "io.ktor:ktor-client-logging-jvm:$ktor_version"
implementation "io.ktor:ktor-client-serialization-jvm:$ktor_version"
}
}
androidTest {
dependencies {
implementation "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"

implementation "io.ktor:ktor-client-mock-jvm:$ktor_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"

// TODO below dependencies can be removed after KT-29343 is fixed
implementation "io.ktor:ktor-client-core-jvm:$ktor_version"
implementation "io.ktor:ktor-client-json-jvm:$ktor_version"
implementation "io.ktor:ktor-client-serialization-jvm:$ktor_version"
implementation "io.ktor:ktor-client-mock-jvm:$ktor_version"
}
}
iosMain {
Expand All @@ -87,6 +91,7 @@ kotlin {
implementation "io.ktor:ktor-client-ios:$ktor_version"
implementation "io.ktor:ktor-client-core-native:$ktor_version"
implementation "io.ktor:ktor-client-json-native:$ktor_version"
implementation "io.ktor:ktor-client-logging-native:$ktor_version"
implementation "io.ktor:ktor-client-serialization-native:$ktor_version"
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package com.karumi.gallery

import android.util.Log

actual fun logError(tag: String, message: String) {
Log.e(tag, message)
actual fun logError(tag: String, message: String, error: Throwable?) {
Log.e(tag, message, error)
}

actual fun logInfo(tag: String, message: String) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ package com.karumi.gallery.app

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext

actual fun launchInMain(block: suspend CoroutineScope.() -> Unit) =
GlobalScope.launch(Dispatchers.Main) { block() }
actual fun CoroutineScope.launchInMain(block: suspend CoroutineScope.() -> Unit) =
launch(Dispatchers.Main) { block() }

actual fun <T> Flow<T>.flowOnBackground(): Flow<T> = flowOn(Dispatchers.Default)

actual fun <T> runBlocking(context: CoroutineContext, block: suspend CoroutineScope.() -> T): T =
kotlinx.coroutines.runBlocking(context, block)
2 changes: 1 addition & 1 deletion shared/src/commonMain/kotlin/com/karumi/gallery/Logger.kt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.karumi.gallery

expect fun logError(tag: String, message: String)
expect fun logError(tag: String, message: String, error: Throwable? = null)
expect fun logInfo(tag: String, message: String)
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.karumi.gallery.app

import com.karumi.gallery.data.PhotosApiClient
import com.karumi.gallery.data.getEngine
import com.karumi.gallery.domain.PhotosFlow
import com.karumi.gallery.generated.KotlinConfig
import com.karumi.gallery.usecase.GetPhotos
import kotlin.native.concurrent.ThreadLocal
Expand All @@ -24,5 +25,8 @@ open class InjectionModule {
PhotosApiClient(getEngine(), KotlinConfig.UNPLASH_KEY)

open fun getPhotos(): GetPhotos =
GetPhotos(getPhotosApiClient())
GetPhotos(getPhotosFlow())

open fun getPhotosFlow(): PhotosFlow =
PhotosFlow(getPhotosApiClient())
}
Original file line number Diff line number Diff line change
@@ -1,48 +1,42 @@
package com.karumi.gallery.app

import com.karumi.gallery.logError
import com.karumi.gallery.logInfo
import com.karumi.gallery.model.PhotoShot
import com.karumi.gallery.model.Photos
import com.karumi.gallery.usecase.GetPhotos
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlin.coroutines.CoroutineContext

class PhotoListPresenter(
private val view: View,
private val getAllPhotos: GetPhotos
) {
) : CoroutineScope {

companion object {
private const val TAG = "PhotoListPresenter"
}
override val coroutineContext: CoroutineContext
get() = job

private var getPhotosJob: Job? = null

fun onCreate() {
view.showLoader()
getPhotosJob = launchInMain {
try {
logInfo(TAG, "Start getting photos")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we lose the logs? I'd prefer to keep those logs to understand in common module how is going the code in both platforms (android or iOS)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nevermind 👍


val allShots = getAllPhotos()
view += allShots
logInfo(TAG, "${allShots.size} photos received")
} catch (ex: Exception) {
logError(TAG, "Load photos error: ${ex.message}")
view.onLoadError()
} finally {
view.hideLoader()
}
}
private val job = Job()

fun onCreate() = launchInMain {
view.render(View.State.Loading)
getAllPhotos()
.flowOnBackground()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👏 👏 👏

.catch { view.render(View.State.Error) }
.collect { view.render(View.State.Success(it)) }
}

fun detachView() {
getPhotosJob?.cancel()
job.cancel()
}

interface View {
operator fun plusAssign(shots: List<PhotoShot>)
fun showLoader()
fun hideLoader()
fun onLoadError()
fun render(state: State)

sealed class State {
object Loading : State()
object Error : State()
data class Success(val photos: Photos) : State()
}
}
}
5 changes: 4 additions & 1 deletion shared/src/commonMain/kotlin/com/karumi/gallery/app/async.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ package com.karumi.gallery.app

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

expect fun launchInMain(block: suspend CoroutineScope.() -> Unit): Job
expect fun CoroutineScope.launchInMain(block: suspend CoroutineScope.() -> Unit): Job

expect fun <T> Flow<T>.flowOnBackground(): Flow<T>

expect fun <T> runBlocking(
context: CoroutineContext = EmptyCoroutineContext,
Expand Down
Loading