3つの画像読み込みライブラリ Glide / Picasso / Coil - JetpackCompose 対応の状況

どれが、今、旬なのか。

まずはリンクを列挙しておきます。

全部使ってみようと思います。

giide vs picasso vs coil

👉 android glide, android picasso, android coil - 調べる - Google トレンド hatena-bookmark

 

Glide


32.8k stars
Watchers 1.1k watching
Forks 6k forks

👉 bumptech/glide: An image loading and caching library for Android focused on smooth scrolling hatena-bookmark

Glide

👉 Glide v4 : Fast and efficient image loading for Android hatena-bookmark

@sjudd Hey, I believe you're one of the maintainers of Glide. Is it a planned feature? Does Glide's team want help from the community on this? Jetpack Compose is going to stable soon, I believe later this month or next month

👉 Jetpack Compose Support · Issue #4459 · bumptech/glide hatena-bookmark

 

Picasso


18.3k stars
Watchers 867 watching
Forks 4k forks

👉 square/picasso: A powerful image downloading and caching library for Android hatena-bookmark

Picasso

👉 Picasso hatena-bookmark

Nobody works on Picasso. If you want something in the next N years definitely use Coil. Or Glide. Or whatever. They're all fine.

Image loading is a terrible, horrible business to be in. It's been really nice not being in that business for the last few years. I don't see a reason to resume. I certainly have no intent to support it anymore. Picasso accomplished its goal of moving the ecosystem out of the painful image loaders of 2011/2012 to the fluent and extensible ones we know today. But it's filled with technical debt and the legacy of poor design (at least, in hindsight) and is currently very, very stuck between a major refactor and redesign with no end in sight.

👉 Consider providing Jetpack Compose support · Issue #2203 · square/picasso hatena-bookmark

 

Coil


8.4k stars
Watchers 98 watching
Forks 512 forks

👉 coil-kt/coil: Image loading for Android backed by Kotlin Coroutines. hatena-bookmark

Coil

👉 Coil hatena-bookmark

To add support for Jetpack Compose, import the extension library:

implementation("io.coil-kt:coil-compose:2.1.0")

👉 Jetpack Compose - Coil hatena-bookmark

 

まとめ

JetpackCompose への対応ライブラリ群も見逃せません。

👉 skydoves/landscapist: 🍂 Jetpack Compose image loading library that fetches and displays network images with Glide, Coil, and Fresco hatena-bookmark

👉 wasabeef/composable-images: The Composable Images is a library providing Jetpack Compose wrapper for Glide, Picasso, and Coil. hatena-bookmark

アーキテクチャー、フレームワーク、ライブラリの選定はそのプロダクトの安定感に直結します。

機能確認を中心に検証しながら、将来の本筋を外してはなりません。

👉 画像読み込みライブラリ「COIL」 hatena-bookmark


@Composable の LifecycleOwner は誰なのか - collectAsStateWithLifecycle

 

Compose までの Flow の collect

coroutine など非同期処理を行う場合ライフサイクルの考慮が必要でしたね!


viewLifecycleOwner.lifecycleScope.launch {
  viewLifecycleOwner.lifecycle.repeatOnLifecycle(STARTED) {
    myViewModel.myUiState.collect {
      // ... 
    }
  }
}

これは、Fragment のビューが STARTED になったときに収集を開始し、RESUMED まで継続し、STOPPED に戻ったときに停止します。

@Composable の LifecycleOwner は誰なのか - collectAsStateWithLifecycle

👉 【MVVM】 Kotlin Flow で使える5つの利用パターン hatena-bookmark

生き死にだけでではないのです。

collect する期間も考えなくてはなりません。

 

Compose では

@Composable 内で、


val items by viewModel.items.collectAsState(initial = emptyList())

というような形で、かんたんに Flow や StateFlow を 収集できます。

しかし、

バックスタック中に、無駄に APIにリクエストしたり、DBにクエリーを投げたりしてません?

逆に、更新されずに古いままの更新されてない画面見せられたりして萎えたりもします。

 

collectAsStateWithLifecycle() の登場

👉 collectAsStateWithLifecycleが追加されたぞ - Qiita hatena-bookmark

所属は以下のようです。

androidx.lifecycle.lifecycle-runtime-compose


implementation "androidx.lifecycle:lifecycle-runtime-compose:2.6.0-alpha01"

実装を見てみます。

ホットな StateFlow と コールドな Flow に向けて2つずつ公開されています。


fun <T> StateFlow<T>.collectAsStateWithLifecycle(
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
    context: CoroutineContext = EmptyCoroutineContext
): State<T> 

fun <T> StateFlow<T>.collectAsStateWithLifecycle(
    lifecycle: Lifecycle,
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
    context: CoroutineContext = EmptyCoroutineContext
): State<T> 

fun <T> Flow<T>.collectAsStateWithLifecycle(
    initialValue: T,
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
    context: CoroutineContext = EmptyCoroutineContext
): State<T>

fun <T> Flow<T>.collectAsStateWithLifecycle(
    initialValue: T,
    lifecycle: Lifecycle,
    minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
    context: CoroutineContext = EmptyCoroutineContext
): State<T>

ライフサイクルや期間を与えて collect 動作を設定できます。

ありがとうございます。

 

LifecycleOwner は誰なのか

前述引用の実装コードより。


...
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
...


LocalLifecycleOwner

ライフサイクルのオーナーといえば、Compose 以前は、

Activity、Fragment、View

ぐらいで考えていましたが。

きっとオーナーは、Activity ではなく、

最上位のルートの @Composable

ではなかろうか。

いや、ワンチャン Activity かもしれん。

見てみましょう。


println("オーナー → ${LocalLifecycleOwner.current}")

 

結果


D: オーナー → androidx.navigation.NavBackStackEntry@4dc222c4

「NavBackStackEntry」さんらしいですわ。

(つづく...)


【Jetpack Compose】ViewModel を捨てて Repository を Composable に直結する

 

気になるのはライフサイクル。

 

きっかけ

フル Compose でよくあるTodoのようなメモのようなアプリを作ってみました。

一通りの機能は実装しました。




👉 Jetpack Compose without ViewModel #shorts - YouTube hatena-bookmark

いろいろ Compose を試しながら進んでいくと ViewModel がスカスカになりました。


@HiltViewModel
class TodoViewModel @Inject constructor(
  private val repository: TodoRepositoryInterface
) : ViewModel() {

  val items: Flow<List<Todo>> = repository.load()

  fun insert(text: String) = repository.insert(text)

  fun update(id: Long, text: String) = repository.update(id, text)

  fun delete(id: Long) = repository.delete(id)

}

ViewModel いらなくね?

ViewModel を省略して、Repository を直結します。

 

結果

以下、少しの書き換えで問題なく動きます。


@Composable
fun TodoScreen(
  //viewModel: TodoViewModel = hiltViewModel()
  repository: TodoRepository = TodoRepository(
    Database(
      AndroidSqliteDriver(
        schema = Database.Schema,
        context = LocalContext.current,
        name = "database.db"
      )
    )
  )
) {


//val items by viewModel.items.collectAsState(initial = emptyList())
val items by repository.load().collectAsState(initial = emptyList())


//viewModel.insert(target.text)
repository.insert(target.text)


//viewModel.update(target.id, target.text) 
repository.update(target.id, target.text)


//viewModel.delete(target.id)
repository.delete(target.id)


//viewModel.delete(target.id)
repository.delete(target.id)

画面回転問題なし、メモリーリークもありません。

すんなりです。

Square製 SQLDelight + Flow(coroutine extension) を使っていますが、

Room + LiveData でもいけると思います。

Composable で Flow(LiveData) を受け取った瞬間に、

collectAsState(ObserveAsState) で State に変換できるんなら、

それのほうが良くね?

ライフサイクルの差も気にしなくていいし。

しかし、緩衝国がなくなるのはなんだか不安です。

Hilt で @Singleton で、ぶち込んでやりたかったです。

あ、でもこれ、 re-compose のたびに、Repository インスタンスが...

(つづく...)

👉 「SwiftUIでMVVMを採用するのは止めよう」と思い至った理由 - Qiita hatena-bookmark
👉 ViewModel はいつ生まれていつ死ぬか 【→ Jetpack Compose】 hatena-bookmark
👉 Jetpack ComposeとViewModelについて考える - Blog - Mori Atsushi hatena-bookmark


【Jetpack Compose】Icon() や Image() で ImageVector をより便利に使う

コード記述のみでベクターのマテリアルアイコン使えます。

drawable の作成が不要なので便利、変更もしやすいです。


Icon(
  imageVector = Icons.Filled.Favorite,
  contentDescription = null
)


Image(
  imageVector = Icons.Filled.Favorite,
  contentDescription = null
)

悪い点としては、

絵柄が49個しかない

絵柄を見ながら選択できない

というところでしょうか。

対応策を考えてみましょう。

 

絵柄が49個しかない

compose 公式のアイコン群(2500個以上)を追加できます。


implementation "androidx.compose.material:material-icons-extended:x.y.z"

エディタのサジェスチョンも大量に増えます。

androidx.compose.material:material-icons-extended

ただ、少し読み込みが遅い。

そこらへんは、公式に注意点があります。

警告: material-icons-extended は大規模なライブラリであり、APK のサイズに影響する可能性があります。そのため、製品版ビルドでは R8/Proguard を使用し、使用されていないリソースを取り除くことを検討してください。また、サイズが大きいために、開発中は、プロジェクトのビルド時間と Android Studio のプレビューの読み込み時間が増加する可能性があります。

👉 Compose のリソース  |  Jetpack Compose  |  Android Developers hatena-bookmark

サイズにも注意する必要があるようです。

 

絵柄を見ながら選択できない

これがすごく困ります。

別で、WEB画面を開くか、Android Studio の Vector Asset Tool を開くかして、絵柄を見て選択して、その名前から、サジェスチョンさせる、くらいしか方法がない。なんかいい方法あったら教えなさいよ。

Material Symbols and Icons - Google Fonts

👉 Material Symbols and Icons - Google Fonts hatena-bookmark

 Vector Asset Tool



将来的には、ライブプレビュー(今現在はリテラルのみ)ですばやく見れるようになるのかもしれません。

Android Studio Electric Eel 以降では、ライブ編集を使用して Compose の開発を高速化できます。ライブ編集は、リテラルのライブ編集をより強力にしたものです。この機能では、プレビューを自動的に更新し、コードの変更をエミュレータまたはデバイスにデプロイすることで、コンポーザブルの更新の影響をリアルタイムで確認できます。

 

👉 Compose のツール  |  Jetpack Compose  |  Android Developers hatena-bookmark

 

まとめ

将来性を見越して、ImageVector を使って


@Composable
fun LikeButton() {
  Button(onClick = {}) {
    Icon(
      imageVector = Icons.Filled.ThumbUp,
      contentDescription = null
    )
    Spacer(Modifier.size(ButtonDefaults.IconSpacing))
    Text("Like")
  }
}

と書きたいです!

Icons.Filled.ThumbUp

ちなみに、これまでのように ベクター drawable を作成して、id で使う記述もできます。


Icon(
  painter = painterResource(id = R.drawable.ic_baseline_favorite_24),
  contentDescription = null
)

しかし、変更時に drawable 消し忘れでゴミが溜まりそう。

あと、

Icons.Default は Icons.Filled のエイリアス

だそうです。

👉 Android Jetpack Compose Icons doesn't contain some of the material icons - Stack Overflow hatena-bookmark

👉 【Jetpack Compose】Compose Settings で数分で設定画面を作る hatena-bookmark


@Composable Scaffold で This material API is experimental and is likely to change or to be removed in the future.

Jetpack Compose で Material3 を使うと、


This material API is experimental and is likely to change or to be removed in the future.

で、ビルド通らず。

AndroidStudio が提案してくる対応としては以下。

@Composable Scaffold で This material API is experimental and is likely to change or to be removed in the future.

アノテーションを付けるのもアレですね。

gradle 側から一括無視しておきましょう。


kotlinOptions {
  allWarningsAsErrors = false
  freeCompilerArgs += [
      "-Xopt-in=kotlin.RequiresOptIn",
      "-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",
      "-Xopt-in=kotlinx.coroutines.FlowPreview",
      "-Xopt-in=kotlinx.serialization.ExperimentalSerializationApi",
      "-Xopt-in=kotlin.Experimental"
  ]
}

👉 Opt-in requirement marker annotation on override requires the same marker on base declaration hatena-bookmark

少し将来に向けて修正。


'-Xopt-in' → '-opt-in'

👉 '-Xopt-in' is deprecated and will be removed in a future release, please use -opt-in instead hatena-bookmark

よって、今回のビルドエラーについてのみで言えば、以下で避けるのが良さげです。


freeCompilerArgs += '-opt-in=androidx.compose.material3.ExperimentalMaterial3Api'

この記述をどこに書くか。

対象が複数になるのを考慮して


freeCompilerArgs += [
    '-opt-in=androidx.compose.material3.ExperimentalMaterial3Api',
]

としておきます。

 

build.gradle (app) allprojects/subprojects {} 内


allprojects { // subproject {
  tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {

    kotlinOptions {
      allWarningsAsErrors = false
      freeCompilerArgs += [
          '-opt-in=androidx.compose.material3.ExperimentalMaterial3Api',
      ]
    }

  }
}

 

build.gradle (module) android {} 内


android {

  kotlinOptions {
    jvmTarget = JavaVersion.VERSION_11.toString()

    allWarningsAsErrors = false
    freeCompilerArgs += [
        '-opt-in=androidx.compose.material3.ExperimentalMaterial3Api',
    ]

  }

 

build.gradle (module) の最後


dependencies {
  // ...
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.9.1'
}

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {

  kotlinOptions {
    allWarningsAsErrors = false
    freeCompilerArgs += [
        '-opt-in=androidx.compose.material3.ExperimentalMaterial3Api',
    ]
  }

}

 

まとめ

プロジェクトの構成に合わせて、多少の拡張性を考慮しながら設定する必要があるでしょう。

👉 Opt-in requirements | Kotlin hatena-bookmark
👉 tachiyomi/build.gradle.kts at master · tachiyomiorg/tachiyomi hatena-bookmark