<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nasrat Sharif Aveek on Medium]]></title>
        <description><![CDATA[Stories by Nasrat Sharif Aveek on Medium]]></description>
        <link>https://medium.com/@nsaveek?source=rss-2cb605fc4602------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y89oQ_nJxbtN7ItjxeVmvw.png</url>
            <title>Stories by Nasrat Sharif Aveek on Medium</title>
            <link>https://medium.com/@nsaveek?source=rss-2cb605fc4602------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:05:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nsaveek/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Android to iOS: Sharing a ViewModel in Kotlin Multiplatform with SKIE — Without Losing Your…]]></title>
            <link>https://nsaveek.medium.com/from-android-to-ios-sharing-a-viewmodel-in-kmm-with-skie-without-losing-your-mind-6197d68c4b82?source=rss-2cb605fc4602------2</link>
            <guid isPermaLink="false">https://medium.com/p/6197d68c4b82</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kmm]]></category>
            <category><![CDATA[shared-viewmodel]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Nasrat Sharif Aveek]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 03:53:48 GMT</pubDate>
            <atom:updated>2026-09-05T04:02:33.760Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Android to iOS: Sharing a ViewModel in Kotlin Multiplatform with SKIE — Without Losing Your Mind</h3><p><em>Part of a series on integrating Swift into Kotlin Multiplatform the right way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fOw9WUdD3uyQC7DVQvXow.png" /></figure><p>If you’re an Android developer starting with Kotlin Multiplatform, there’s a moment almost everyone reaches.</p><p>You’ve moved your business logic into commonMain. Your API calls work. Your repository works. Your use cases work. Your MVI ViewModel works. Your StateFlow is happily emitting states.</p><p>Then you open Xcode.</p><p>Suddenly, you’re staring at ObservableObject, @Published, Task, async/await — and an error that just says:</p><blockquote><em>“Cannot find type in scope.”</em></blockquote><p>The natural question at this point is: <strong><em>how am I supposed to use my Kotlin ViewModel from SwiftUI?</em></strong></p><p>This article is for exactly that developer. If you already understand Android’s ViewModel, StateFlow, coroutines, and MVI, you already know most of what you need. You don&#39;t need to become an iOS expert first — you just need to understand the small translation layer between Kotlin/KMM/KMP and SwiftUI.</p><h3>What we’re trying to achieve</h3><p>Say we have a shared ViewModel:</p><pre>class StockListViewModel(<br>    private val getStocks: GetStocksUseCase<br>) : ViewModel() {</pre><pre>    private val _uiState =<br>        MutableStateFlow&lt;StockListUiState&gt;(StockListUiState.Loading)</pre><pre>    val uiState: StateFlow&lt;StockListUiState&gt; =<br>        _uiState.asStateFlow()</pre><pre>    fun event(action: StockListAction) {<br>        // MVI event handling<br>    }<br>}</pre><p>On Android, this feels completely natural. Compose observes the state:</p><pre>val state by viewModel.uiState.collectAsState()<br>or <br>val state by viewModel.uiState.collectAsStateWithLifecycle()</pre><p>And user interactions send events straight back.</p><pre>viewModel.event(StockListAction.LoadStocks)</pre><p>So far, so good. But what happens on iOS? SwiftUI doesn’t consume StateFlow the way Compose does — and this is exactly where <strong>SKIE</strong> earns its keep.</p><h3>What SKIE actually solves</h3><p><a href="https://skie.touchlab.co/">SKIE</a>, from Touchlab, improves Kotlin-to-Swift interoperability. Two of its capabilities matter most for this problem:</p><p><strong>Flow / StateFlow.</strong> Kotlin flows can be exposed so Swift consumes them through its native asynchronous sequence model — instead of wrestling with collect { }, you get:</p><pre>for await value in viewModel.uiState {<br>    // state changed<br>}</pre><p><strong>Sealed classes.</strong> If your UI state or actions are modeled as Kotlin sealed hierarchies, SKIE makes them genuinely pleasant to work with from Swift.</p><p>The goal isn’t to recreate your ViewModel in Swift — it’s to let SwiftUI talk to the <em>same</em> shared ViewModel.</p><h3>The mental model: Android vs. iOS</h3><p>Before looking at Swift code, translate the concepts you already know.</p><p>On Android:</p><pre>viewModelScope.launch {<br>    viewModel.uiState.collect { state -&gt;<br>        // update state<br>    }<br>}</pre><p>On iOS:</p><pre>Task {<br>    for await state in viewModel.uiState {<br>        // update state<br>    }<br>}</pre><p>The syntax changed. The mental model didn’t. You’re still: starting asynchronous work, collecting state, updating the UI, and cancelling that work when it’s no longer needed. Once you see that, Swift becomes a lot less intimidating.</p><h3>Where does the Swift code live?</h3><p>Should the SwiftUI screen talk directly to the Kotlin ViewModel? Technically, yes. But I prefer a very small Swift-side wrapper — an adapter between the shared ViewModel and SwiftUI:</p><pre>import SwiftUI</pre><pre>@MainActor<br>final class StockListObservable: ObservableObject {</pre><pre>    @Published private(set) var state: StockListUiState</pre><pre>    private let viewModel: StockListViewModel<br>    private var observeTask: Task&lt;Void, Never&gt;?</pre><pre>    init() {<br>        self.viewModel = IosViewModels().stockListViewModel()<br>        self.state = viewModel.uiState.value<br>    }<br>}</pre><p>There’s already a lot of familiar Android thinking hiding in this small piece of Swift.</p><h3>@MainActor — think main thread</h3><p>On Android, you’re deliberate about which thread updates the UI: Dispatchers.Main, @MainThread. In Swift concurrency, the equivalent is @MainActor — it isolates the object to the main actor, which is exactly where UI state updates should happen. When you see @MainActor final class StockListObservable, just read it as: <em>this is my UI/main-thread state holder.</em></p><h3>Why ObservableObject?</h3><p>This is where SwiftUI diverges from Compose. Compose can collect a StateFlow directly and drive recomposition from it. SwiftUI relies on its own observation mechanism — traditionally ObservableObject with @Published. So the wrapper holds:</p><pre>@Published private(set) var state: StockListUiState</pre><p>The shared ViewModel still owns the actual application state. The Swift wrapper just republishes changes in a form SwiftUI understands:</p><pre>KMP StateFlow → Swift bridge (@Published) → SwiftUI</pre><p>We’re not creating a second ViewModel — we’re creating a platform-specific presentation adapter.</p><h3>Getting the ViewModel from Koin</h3><p>Dependency injection is another common stumbling block. On Android you might have:</p><pre>val viewModel: StockListViewModel = koinViewModel()</pre><p>It feels effortless — but Swift has no access to that Compose-specific integration. So expose a small Kotlin bridge instead:</p><pre>class IosViewModels : KoinComponent {<br>    fun stockListViewModel(): StockListViewModel = get()<br>}</pre><p>The exact shape can vary with your Koin setup, but the idea stays the same: don’t make Swift understand your entire DI graph — give it a small, explicit entry point.</p><pre>self.viewModel = IosViewModels().stockListViewModel()</pre><h3>The part that usually confuses Android developers</h3><p>We now have the ViewModel and a @Published property — but how does state actually get updated?</p><p>On Android: viewModel.uiState.collect { state -&gt; ... }. With SKIE, Swift consumes the same flow as an async sequence:</p><pre>for await value in viewModel.uiState {<br>    self.state = value<br>}</pre><p>Wrapped in a Task:</p><pre>func activate() {<br>    observeTask?.cancel()<br>    observeTask = Task { [weak self] in<br>        guard let self else { return }<br>        for await value in self.viewModel.uiState {<br>            self.state = value<br>        }<br>    }<br>}</pre><p>That’s the key piece of this whole article. Mentally, it’s identical to:</p><pre>viewModelScope.launch {<br>    viewModel.uiState.collect { value -&gt;<br>        state = value<br>    }<br>}</pre><h3>Why activate()?</h3><p>You could start collecting inside init(). I prefer making the lifecycle explicit — it&#39;s easier to reason about:</p><pre>func deactivate() {<br>    observeTask?.cancel()<br>    observeTask = nil<br>}</pre><p>The mental model is simple: activate() ≈ launch + collect, deactivate() ≈ Job.cancel().</p><h3>Wiring up MVI</h3><p>The bridge also needs to send intentions back to the shared ViewModel. Given:</p><pre>sealed interface StockListAction {<br>    data object LoadStocks : StockListAction<br>    data object RefreshStocks : StockListAction<br>}</pre><p>SKIE exposes the singleton actions to Swift, so the wrapper can provide:</p><pre>func load() {<br>    viewModel.event(action: StockListActionLoadStocks.shared)<br>}</pre><pre>func refresh() {<br>    viewModel.event(action: StockListActionRefreshStocks.shared)<br>}</pre><p>Now the full MVI loop is in place:</p><pre>SwiftUI → user interaction → Swift bridge → viewModel.event(action:)<br>   → Shared ViewModel → StateFlow → Swift bridge → @Published → SwiftUI</pre><p>The MVI logic still lives entirely in shared Kotlin code. One ViewModel, two platforms — and this is where the architecture starts to click:</p><pre>Shared layer:  ViewModel → MVI events → UI state → Use Cases → Repository → API/DB</pre><pre>Android:  Compose → collectAsState() → Shared ViewModel<br>iOS:      SwiftUI → ObservableObject → SKIE → Shared ViewModel</pre><p>The shared ViewModel doesn’t need to know which platform is consuming it. That’s the real payoff.</p><h3>Using the bridge from SwiftUI</h3><p>The SwiftUI screen itself ends up refreshingly boring — which is exactly the point:</p><pre>struct StockListView: View {</pre><pre>    @StateObject private var vm = StockListObservable()</pre><pre>    var body: some View {<br>        List(vm.state.listOfStocks, id: \.name) { stock in<br>            Text(stock.name)<br>        }<br>        .overlay {<br>            if vm.state.isLoading {<br>                ProgressView()<br>            }<br>        }<br>        .task { vm.activate() }<br>        .onDisappear { vm.deactivate() }<br>    }<br>}</pre><p>If you’re coming from Compose, .task and .onDisappear should feel familiar — roughly LaunchedEffect { collect() } on the way in, and cancelling collection on the way out.</p><h3>Handling sealed UI states</h3><p>This is another place SKIE shines. Given:</p><pre>sealed interface StockListUiState {<br>    data object Loading : StockListUiState<br>    data class Data(val stocks: List&lt;Stock&gt;) : StockListUiState<br>    data class Error(val message: String) : StockListUiState<br>}</pre><p>Android naturally reaches for when. With SKIE, Swift gets something just as clean:</p><pre>switch onEnum(of: vm.state) {<br>case .loading:<br>    ProgressView()<br>case .data(let data):<br>    StockList(data.stocks)<br>case .error(let error):<br>    ErrorView(error.message)<br>}</pre><p>This is one of those moments where the Kotlin/Swift boundary stops feeling painful — instead of fighting generated interop types, you work with the state hierarchy almost as if it were native Swift.</p><h3>The one gotcha to remember</h3><p>On Android, the framework and viewModelScope give you a well-defined lifecycle for free. On iOS, your Swift subscription is something <em>you</em> manage deliberately — that&#39;s why the wrapper keeps and explicitly cancels its own observeTask.</p><p>This doesn’t mean KMM/KMP has no lifecycle management. It means the Swift-side collection task has its <em>own</em> lifecycle, separate from the shared ViewModel’s. If your shared ViewModel owns work that needs explicit cleanup, expose a proper cleanup API from the shared layer — don’t assume cancelling the Swift-side collection cancels everything inside the ViewModel too.</p><h3>The complete bridge</h3><p>Putting it all together, the bridge is small:</p><pre>import SwiftUI</pre><pre>@MainActor<br>final class StockListObservable: ObservableObject {</pre><pre>    @Published private(set) var state: StockListUiState</pre><pre>    private let viewModel: StockListViewModel<br>    private var observeTask: Task&lt;Void, Never&gt;?</pre><pre>    init() {<br>        self.viewModel = IosViewModels().stockListViewModel()<br>        self.state = viewModel.uiState.value<br>    }</pre><pre>    func activate() {<br>        observeTask?.cancel()<br>        observeTask = Task { [weak self] in<br>            guard let self else { return }<br>            for await value in self.viewModel.uiState {<br>                self.state = value<br>            }<br>        }<br>    }</pre><pre>    func deactivate() {<br>        observeTask?.cancel()<br>        observeTask = nil<br>    }</pre><pre>    func load() {<br>        viewModel.event(action: StockListActionLoadStocks.shared)<br>    }</pre><pre>    func refresh() {<br>        viewModel.event(action: StockListActionRefreshStocks.shared)<br>    }<br>}</pre><p>Notice what this file <em>doesn’t</em> contain: no API logic, no business rules, no repository logic, no MVI state transitions, no database logic, no use cases. It only translates Kotlin into Swift, and shared state into SwiftUI observation. That’s exactly what it should do.</p><h3>The bigger lesson</h3><p>When moving from Android to KMM/KMP, it’s tempting to think <em>“I need to learn Swift before I can touch the iOS side.”</em> I don’t think that’s the right way in.</p><p>Start with what you already know:</p><p>You already know (Kotlin) Learn the equivalent (Swift) collect { } for await launch { } Task { } Job.cancel() Task.cancel() StateFlow AsyncSequence (via SKIE) State @Published</p><p>You already understand ViewModel, StateFlow, coroutines, and MVI. You just need to learn how Swift expresses those same concepts.</p><h3>You don’t need to rewrite your ViewModel for iOS</h3><p>That’s ultimately the point. Your shared Kotlin ViewModel stays the single source of truth. Android consumes it through Compose. iOS consumes it through a small Swift bridge. The UI stays platform-native. The business logic stays shared. The architecture stays consistent — and the amount of Swift you actually need to write is surprisingly small.</p><p>If you’re an Android developer who’s been avoiding the iOS side of KMM/KMP because Swift interop looks intimidating: start here. Don’t try to learn the whole iOS ecosystem at once. Learn the bridge. Once StateFlow → AsyncSequence, collect → for await, launch → Task, and cancel → Task.cancel() click into place, the rest gets a lot easier.</p><p><strong>Same ViewModel. Same StateFlow. Same MVI. Different UI. One shared brain, two thin heads.</strong> 🧠</p><p><em>Next in the series: Exposing Kotlin suspend functions as native Swift async/await with SKIE.</em></p><p>#KotlinMultiplatform #KMM #Android #iOS #SwiftUI #Kotlin #SKIE #MVI #JetpackCompose #MobileDevelopment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6197d68c4b82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2. Create a complete Android app from scratch ~ Retrofit — Dagger2 — Room — MVVM and LiveData]]></title>
            <link>https://nsaveek.medium.com/2-create-a-complete-android-app-from-scratch-retrofit-dagger2-room-mvvm-and-livedata-d658e2f28771?source=rss-2cb605fc4602------2</link>
            <guid isPermaLink="false">https://medium.com/p/d658e2f28771</guid>
            <category><![CDATA[room]]></category>
            <category><![CDATA[room-database]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[Nasrat Sharif Aveek]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 10:29:25 GMT</pubDate>
            <atom:updated>2021-02-08T14:20:09.663Z</atom:updated>
            <content:encoded><![CDATA[<h3>2. Create a complete Android app from scratch ~ Retrofit — Dagger2 — Room — MVVM and LiveData</h3><p>Instantiate and use Room Database with Dagger inside the project.</p><p>In Part1, we have shown how we have implemented Dagger in our project as Dependency Injection. This time, we are going to use Room database to store City’s information inside our app. We will also see how we can instantiate Room using Dagger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNtOOKdjqqATLIivXJmwiA.png" /><figcaption>Demo Weather App</figcaption></figure><h3>Here are the parts we are going to see.</h3><ol><li><a href="https://medium.com/@nsaveek/create-a-complete-android-app-from-scratch-retrofit-dagger2-room-mvvm-and-livedata-92052987ff59"><em>Introduce yourself with Dagger</em></a></li><li><strong><em>Try Room Database to store data</em></strong></li><li><em>Get a grasp with MVVM ( Model- View- ViewModel)</em></li><li><em>Make yourself comfortable with LiveData and Databinding</em></li><li><em>Know Retrofit with example</em></li><li><em>Bonus : We will see Rx in action</em></li></ol><h3>What is Room?</h3><p>According to Google...</p><pre>The <a href="https://developer.android.com/training/data-storage/room">Room</a> persistence library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.</pre><h3>How to use?</h3><pre>dependencies {<br>  def room_version = &quot;2.2.5&quot;<br><br>  implementation &quot;androidx.room:room-runtime:$room_version&quot;<br>  annotationProcessor &quot;androidx.room:room-compiler:$room_version&quot; // For Kotlin use kapt instead of annotationProcessor<br><br>  // optional - Kotlin Extensions and Coroutines support for Room<br>  implementation &quot;androidx.room:room-ktx:$room_version&quot;<br><br>  // optional - RxJava support for Room<br>  implementation &quot;androidx.room:room-rxjava2:$room_version&quot;<br><br>  // optional - Guava support for Room, including Optional and ListenableFuture<br>  implementation &quot;androidx.room:room-guava:$room_version&quot;<br><br>  // Test helpers<br>  testImplementation &quot;androidx.room:room-testing:$room_version&quot;<br>}</pre><h3>How do we provide Room instance with Dagger?</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4446e6bb7ca66a282111a97cbaa10c9/href">https://medium.com/media/f4446e6bb7ca66a282111a97cbaa10c9/href</a></iframe><p>If you remember the flow that we shared in part1, the AppModule have the connection with RoomModule.</p><figure><img alt="The class design flow." src="https://cdn-images-1.medium.com/max/644/1*7PnuQFN8ny6dKJ2VISE6Yg.jpeg" /><figcaption>Flow of the class</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1702e9a77665ee17e8c7606d04ba5cf1/href">https://medium.com/media/1702e9a77665ee17e8c7606d04ba5cf1/href</a></iframe><p>We are using a <a href="https://medium.com/@nsaveek/repository-pattern-in-android-e6ebbc16595f">Repository Design Pattern</a> to use Room Database for CRUD operation. You can learn more on Repository Pattern <a href="https://medium.com/@nsaveek/repository-pattern-in-android-e6ebbc16595f">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f28dcd2dd54bd47b12600f2e6563d997/href">https://medium.com/media/f28dcd2dd54bd47b12600f2e6563d997/href</a></iframe><p>So you can see we are using <strong>ILocalStorageRepository</strong> and overriding <strong>insertWeatherDataIntoLocalStorage(model : WeatherModel), </strong>then using weatherDao.insert(model) to insert data inside Room Database. Let’s see what’s inside weatherDao class.</p><pre><strong>interface </strong>BaseDAO &lt;T&gt;{<br>    @Insert<br>    <strong>fun </strong>insert(model : T)<br><br>    @Delete<br>    <strong>fun </strong>delete(model: T)<br><br>    @Update<br>    <strong>fun </strong>update(model : T)<br>}</pre><pre>@Dao<br><strong>interface </strong>WeatherDAO : BaseDAO&lt;WeatherModel&gt; {<br><br>    @Query(<strong>&quot;SELECT * FROM `weathermodel`&quot;</strong>)<br>    <strong>fun </strong>getAllData() : LiveData&lt;List&lt;WeatherModel&gt;&gt;<br>}</pre><p>N.B: You may have noticed, we are using LiveData to get all data information. This is because we want to trigger loading data from the database whenever there is a change detected. Usually, right after adding a city, we would like to see the city is visible in the list.</p><p>The entity is here..</p><pre>@Entity<br><strong>data class </strong>WeatherModel (<br>        @PrimaryKey <strong>var uid </strong>: String,<br>        @ColumnInfo(name = <strong>&quot;name&quot;</strong>) <strong>var cityName </strong>: String?,<br>        @Ignore <strong>var type </strong>: String? = <strong>null<br></strong>){<br>    <strong>constructor</strong>():<strong>this</strong>(<strong>&quot;&quot;</strong>,<strong>&quot;&quot;</strong>,<strong>&quot;&quot;</strong>)<br>}</pre><p>Now, you can insert the data inside Room database using your preferred architecture. I have used MVVM architecture here.</p><pre><strong>private fun </strong>insertDataToDatabase(data: String) {<br>    <strong>compositeDisposable</strong>.add(<br>        Completable.fromAction <strong>{<br>            val </strong>thread = Thread <strong>{<br>                viewModel</strong>.insertDataInsideWeatherDB(WeatherModel(UUID.randomUUID().toString(), cityName = data))<br>            <strong>}<br>            </strong>thread.start()<br>        <strong>}</strong>.subscribeOn(Schedulers.io())<br>            .observeOn(AndroidSchedulers.mainThread())<br>            .subscribe(<strong>this</strong>@MainActivity::successInsertionData, <strong>this</strong>@MainActivity::errorCallback)<br>    )<br>}</pre><p>Check the <a href="https://github.com/NsAveek/Demo-Weather-App">repository</a> to find out how we have implemented Clean Architecture.</p><p>In the next part of this series, we will see how we can implement MVVM architecture with the help of Dagger. Hope you will find the write-up useful and don’t forget to clap 👏 👏 .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d658e2f28771" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a complete Android app from scratch ~ Retrofit - Dagger2 - Room - MVVM and LiveData]]></title>
            <link>https://nsaveek.medium.com/create-a-complete-android-app-from-scratch-retrofit-dagger2-room-mvvm-and-livedata-92052987ff59?source=rss-2cb605fc4602------2</link>
            <guid isPermaLink="false">https://medium.com/p/92052987ff59</guid>
            <category><![CDATA[room]]></category>
            <category><![CDATA[retrofit2]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Nasrat Sharif Aveek]]></dc:creator>
            <pubDate>Mon, 01 Jun 2020 09:17:12 GMT</pubDate>
            <atom:updated>2020-06-11T10:34:31.061Z</atom:updated>
            <content:encoded><![CDATA[<p>And Of course <strong>Kotlin</strong> with <strong>Clean Architecture</strong>!</p><p>Hi everyone, welcome back to one of my favorite places. As I consider myself lazy and can’t manage time for write up; I have motivated myself for something that can help a lot of developers just like it helped me.</p><p>Today, I will be sharing with you mostly code blocks that you can run and see the practical implementation of Retrofit, Room, Dagger2, ViewModel and to communicate with the views; LiveData.</p><p>I will also use Repository design pattern and Kotlin as my primary language. Just take note, I am not going to share these concepts in detail as this write up is more code explanation than theory. To add, this write-up requires patience because there are lots of areas to explain even though I want to make it short.</p><blockquote>Let’s start..</blockquote><blockquote>Below is the screenshot of the app we are going to develop.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yB0qem3ArIjM0s-W3-Mlbw.png" /><figcaption>Demo Weather App</figcaption></figure><p>I am separating each of the modules for this write-up. This project is also an example of <strong>Clean Architecture. </strong>I have used multiple recycler views and constraint layout to build up the UI. Kindly ignore the UI issues as this post is only focused on the app performance and architecture.</p><ol><li><strong><em>Introduce yourself with Dagger</em></strong></li><li><a href="https://medium.com/@nsaveek/2-create-a-complete-android-app-from-scratch-retrofit-dagger2-room-mvvm-and-livedata-d658e2f28771"><em>Try Room Database to store data</em></a></li><li><em>Get a grasp with MVVM ( Model- View- ViewModel)</em></li><li><em>Make yourself comfortable with LiveData and Databinding</em></li><li><em>Know Retrofit with example</em></li><li><em>Bonus : We will see Rx in action</em></li></ol><p>We will be covering as much as we can for the first part which is completely about dagger; the dependency injection framework.</p><p>I will not go in detail about what is dependency injection, how it works rather we will see the code in action. At the bottom of the write-up, I will add some references from where you can know details about the dependency injection and dagger framework.</p><p>First thing first, <strong>What is dependency injection?</strong>. Let’s understand dependency first. From general understanding, to build something we are dependent on some other things. For instance, we need woods, power jointers, hacksaw, joinery gadgets, hammer, screwdrivers, etc. to build a house. That means, to create a house we need these “tools” to be present at the place which are dependency for the house and the house is dependant on these tools. So, we must bring these tools to the place where we are going to build the house. Now, think from the code perspective; The house is the dependant which is the software we are going to build. Then the tools are needed to bring where the house is being made or simply the tools are “injected” if you consider the coding perspective.</p><p>Before going into details, let me explain the responsibilities of the classes I have written briefly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*7PnuQFN8ny6dKJ2VISE6Yg.jpeg" /><figcaption>Dependency flow for Weather App</figcaption></figure><p>In our project, we are going to create -</p><p><strong>BaseDI.kt : </strong>Responsible for containing all necessary Modules, Components and Dependency builders.</p><p><strong>AppInjector.kt :</strong> Responsible for tying up the Activities-Fragments with Dagger. I am going through these briefly. But honestly, you need to read more about DI/ DI Framework if you are a beginner programmer or have a little/zero concept of this part. Please check the references added at the bottom of the writeup.</p><p><strong>BaseApp.kt :</strong> Responsible to ask AppInjector.kt to initiate app injection. Basically, in the background, dagger is smart enough to know what to inject and how.</p><pre>DaggerAppComponent.builder()<br>        .application(app) <em>// AppModule bindsInstance of App<br>        </em>.build()<br>        .inject(app)</pre><p><strong>Modules :</strong> We can refer these as the “tools” I mentioned above. So basically, we need these “tools” in order to build the “house”.</p><p>How to use? <br><em>Add @Modules annotation on top of the </em><strong><em>class</em></strong></p><pre>@Module<br>class RetrofitModule {    <br>  @Provides    <br>  @Singleton    <br>  fun provideRetrofitInstance() : Retrofit {<br>        return Retrofit.Builder()<br>          .baseUrl(baseUrl)<br>          .addConverterFactory(GsonConverterFactory.create())<br>          .addCallAdapterFactory(RxJava2CallAdapterFactory.create())<br>              .build()<br>    }<br>  }</pre><p><strong>Components : </strong>This is the mediator between the “house” and “tools”. Meaning, a module can not directly provide anything unless it’s been tied by a component.</p><p>How to use?<br><em>Add @Component annotation on top of the </em><strong><em>interface</em></strong><em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec4481e342d67516ebd9fae9bff4b66d/href">https://medium.com/media/ec4481e342d67516ebd9fae9bff4b66d/href</a></iframe><p><strong>Provides :</strong> These are the “tools” needed to be provided in order to build the house. These “tools” can be provided by the Modules only.</p><p>How to use?<br><em>Add @Provides annotation on top of the </em><strong><em>function/method</em></strong><em>.</em></p><pre>@Provides    <br>@Singleton    <br>fun provideContext (application: Application) : Context {        return application    <br>}</pre><p><strong>Inject :</strong> The “tools” provided by the Modules using @Provides needed to be injected wherever we want to use that.</p><p>How to use?<br><em>Add @Inject annotation on top of the </em><strong><em>member variable</em></strong> or as constructor.</p><pre>class MainActivity : NetworkActivity(), LifecycleOwner, HasSupportFragmentInjector { <br>    @Inject    <br>    lateinit var viewModelProviderFactory: ViewModelProviderFactory<br>}</pre><p><strong>BindsInstance :</strong> Binds a particular object instance with the app.</p><pre>@Component.Builder<br><strong>interface </strong>Builder {<br>    @BindsInstance <em>// Binds a particular instance of the object through the component of the time of construction<br>    </em><strong>fun </strong>application(application: Application): Builder <em>// This makes the application available through all modules available<br><br>    </em><strong>fun </strong>build(): AppComponent<br>}</pre><p><strong>Scope</strong> : Scoping is another important topic to understand Dagger. If you just want to know briefly, then I would say Scoping is the area where you want to limit your <strong>injected “tools”</strong> to be available. For instance, we call it <strong><em>ApplicationScope</em></strong> if you want the “tools” to be available throughout the entire app lifecycle. Meaning to say, if you want any particular function or instance to be available on whichever class you want, On the other hand, <strong><em>ActivityScope </em></strong>limits the availability to the particular activity only. Similarly <strong><em>FragmentScope, ViewModelScope </em></strong>etc. are used accordingly.</p><blockquote>One good example of the ApplicationScope is Singleton functions or classes, which we need to use throughout the app lifecycle. Let’s consider Retrofit or Room or SharedPreference instance, which we need to use from any activities or fragments based on the requirement, so we create it under ApplicationScope so that we get the same instance whenever we need to use that.</blockquote><blockquote>Similarly, if we want to use any particular instance only inside the MainActivity, we can create inside the MainActivityScope.</blockquote><h4><strong>It’s not clear, how can we create these scopes?</strong></h4><p>Well, scope is something for you to understand, to create it inside the application, we create modules. For ApplicationScope, in this project, I have created <strong><em>AppModule</em></strong>, which contains all the necessary “<strong><em>tools” </em></strong>I will be needing anywhere in the application with the same instance. Obviously, you can name it as you wish. 🙂</p><p>Similarly, we can create <strong><em>MainActivitySubComponent,</em></strong> for the “<strong><em>tools” </em></strong>we need to use inside MainActivity only.</p><h4>Still not clear, from where did you bring Subcomponent?</h4><p>Briefly, subcomponents are those components that are extended from parent components and exposable to the defined scope only.</p><pre>@Module<br><strong>internal abstract class </strong>MainActivityFragmentsProvider {<br>    @ContributesAndroidInjector(modules = [CitiesBottomSheetVMModule::<strong>class</strong>])<br>    <strong>abstract fun </strong>bindCitiesBottomSheetFragment(): CitiesBottomSheetFragment<br>}</pre><p>Here, in our code, we can notice, we have mentioned “modules = CitiesBottomSheetVMModule::class”. This class/module is under CitiesBottomSheetFragment Subcomponent and we create the subcomponent automatically when we write <strong>@ContributesAndroidInjector. </strong>Whichever modules we add here, are under <strong>CitiesBottomSheetFragmentScope </strong>as well as<strong> CitiesBottomSheetFragment subcomponent.</strong></p><p>So, here is the flow about how dagger connects altogether.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec4481e342d67516ebd9fae9bff4b66d/href">https://medium.com/media/ec4481e342d67516ebd9fae9bff4b66d/href</a></iframe><ol><li>AppComponent adds AndroidSupportInjectionModule::class and extends from AndroidInjector&lt;BaseApp&gt; which lets dagger know this is the component to look for when it injects the app</li><li>BaseApp then calls AppInjector.init(context) to initiate dagger inside the app. You can directly initiate here as well if you don’t want to isolate the code using AppInjector.</li><li>AppComponent also adds AppModule, LocalDependencyBuilderModule, ViewModelFactoryModule etc. which are under AppComponent(Parent component).</li><li>LocalDependencyBuilderModule contains all the activities with its subcomponents.</li><li>The MainActivity under its subcomponent, connects CitiesBottomSheetFragment using MainActivityFragmentsProvider which have its own subcomponent.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18f0c87cad3644331cc5bd81e6eda95d/href">https://medium.com/media/18f0c87cad3644331cc5bd81e6eda95d/href</a></iframe><p>You can find the project here. you can star the project if you wish to.</p><p><a href="https://github.com/NsAveek/Demo-Weather-App">NsAveek/Demo-Weather-App</a></p><p>In the next part of this write-up, I will share how can we store and retrieve data using Room database. Until then, take a close look at the project, try to explore as much as you can. I will be happy to answer any questions regarding the app.</p><p>Reference : At the beginning of the write-up, I mentioned I will add some references which possibly can help readers to understand better in-depth. Here are the references below.</p><p>Raywenderlich :</p><p><a href="https://www.raywenderlich.com/6583167-dagger-2-tutorial-for-android-advanced">Dagger 2 Tutorial For Android: Advanced</a></p><p>Codingwithmitch :</p><p><a href="https://codingwithmitch.com/courses/dagger22-android/demo/">CodingWithMitch.com</a></p><p>GitHubBrowserSample :</p><p><a href="https://github.com/android/architecture-components-samples/tree/master/GithubBrowserSample">android/architecture-components-samples</a></p><p>Have a good day. 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92052987ff59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Confused Kotlin!  Forget theory, Trust the code ]]></title>
            <link>https://nsaveek.medium.com/confused-kotlin-forget-theory-trust-the-code-14c04c1d0844?source=rss-2cb605fc4602------2</link>
            <guid isPermaLink="false">https://medium.com/p/14c04c1d0844</guid>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[standard-function]]></category>
            <category><![CDATA[code-example]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Nasrat Sharif Aveek]]></dc:creator>
            <pubDate>Thu, 21 Nov 2019 16:41:30 GMT</pubDate>
            <atom:updated>2019-11-21T16:41:30.662Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discussion with code example on <strong><em>higher order function</em>, <em>run, also, apply, let, with &amp; when</em></strong> etc.</h4><h4>Let’s clear the confusion 💪</h4><p><strong>Higher Order Function<em> :</em></strong> One of the excellent features of Kotlin is Higher Order Function. In a nutshell, this is a special type of function which takes function as a parameter and invokes that function to perform operation.</p><p>Let’s take an example from Android App development ..</p><p>Consider your activity contains multiple fragments and you add or replace them on different actions taken by the user. Meaning to say, if you have a MainActivity and three fragments named FragA, FragB and FragC. By default you load FragA with MainActivity. Later if user presses ButtonB, you replace FragA with FragB and if ButtonC, you replace FragA with FragC.</p><p>Simply you can do it with Three different functions or Two or maybe One. Let’s see how we can solve this part of the code with Higher Order Function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/306087125e0706403374b2fc20d93555/href">https://medium.com/media/306087125e0706403374b2fc20d93555/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*83MTH91o3phR9Zswtw7T7w.png" /><figcaption>Flow chart of Use-case for Standard Function</figcaption></figure><p><strong>Apply :</strong> Consider yourself as an object. You want to modify some of the part of you and return the full object containing modified part; use apply().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63501f3e6805186c7301c43856fba165/href">https://medium.com/media/63501f3e6805186c7301c43856fba165/href</a></iframe><p><strong>Also :</strong> You are the object but you can not modify your parts without explicitly given consent, at the same time you want to return the object; Use also().</p><blockquote>When to use Apply and when to use Also ?</blockquote><p>Object creation can be one of the best examples for using Apply(). Instantiate one object and then assign values to its properties. Once done assigning, return the object.</p><p>If you have any other plan to do with the Object, for instance to prepare some log with the updated Object, try Also().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a07207eafc2007b2837a100d38f3ce0/href">https://medium.com/media/5a07207eafc2007b2837a100d38f3ce0/href</a></iframe><p><strong>Let : </strong>Mainly we use let to check null values in Android. For instance, if you want to do some property value change only when the object is not null; you can go for it.</p><p>Please have a look at the code example below to understand the functionality</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/857278682d3cfe880900aed2965ea937/href">https://medium.com/media/857278682d3cfe880900aed2965ea937/href</a></iframe><p><strong>Run : </strong>If you want to limit your variable scoping, go for <strong><em>run </em></strong><em>. </em>Meaning to say, when using too many variables inside a block of code you can easily identify and separate modifying the code to the specific area only.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81fcf5be391167da6fd75cf4068eb3e3/href">https://medium.com/media/81fcf5be391167da6fd75cf4068eb3e3/href</a></iframe><p>A practical example can be ..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avNdgmdld-uaMEnNsv9Xbw.png" /></figure><p>See, how we have manipulated data inside the run scope. the “balanceText” could use <strong><em>run</em></strong> and set value like this, but that would have a separated scope and could easily identified.</p><p><strong>With : </strong>The above screenshot is also an example of using <strong><em>with.</em></strong> How we have accessed the value of the viewmodel smartly. See the difference of using and not using <strong><em>“with” </em></strong>below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbd03ded33b2a7c742729fe79557040e/href">https://medium.com/media/dbd03ded33b2a7c742729fe79557040e/href</a></iframe><p>On a large context, that will surely make you scratch on your head.</p><p><strong>When : </strong>When is mainly an expression. It works like switch-case in java and returns something.</p><p>From <a href="https://kotlinlang.org/docs/">https://kotlinlang.org/docs/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K75O-yAac-pWmYD5uI1vCw.png" /></figure><p>Also, you can have a look at the Higher order function example added on top of this article.</p><p>Hopefully, I have cleared a bit of your confusion regarding use case of these parts of Kotlin. My writeup will be successful if it helps even a person struggling understanding of these. I will be happy to share more if anyone wants to know. The comment section is always open. Peace ✌️</p><p>Reference :</p><ul><li><a href="https://kotlinexpertise.com/coping-with-kotlins-scope-functions/">Kotlin Scope Functions: let, run, apply, also, with - Kotlin Expertise Blog</a></li><li><a href="https://stackoverflow.com/a/45978893/963400">Example of when should we use run, let, apply, also and with on Kotlin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14c04c1d0844" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code like a coder! Code for others\_^_/ #Programmers’ talk]]></title>
            <link>https://nsaveek.medium.com/code-like-a-coder-code-for-others-programmers-talk-2f2f6847e4e3?source=rss-2cb605fc4602------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f2f6847e4e3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dos-and-donts]]></category>
            <category><![CDATA[experience]]></category>
            <category><![CDATA[life-lessons]]></category>
            <dc:creator><![CDATA[Nasrat Sharif Aveek]]></dc:creator>
            <pubDate>Thu, 31 Oct 2019 09:19:25 GMT</pubDate>
            <atom:updated>2021-02-08T16:12:34.711Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>“I am a programmer”</strong> this title no longer belongs to someone who just knows the programming language and builds software with the language. There are plenty of languages available for different platforms nowadays. It’s been a long time we have seen upgrades of the codes/frameworks( known as versions); new languages have been introduced on top of other languages to make an efficient program with ease.</p><p>This article is all about sharing some tips and guidelines to write an efficient program. Most of the experienced programmers have already experience developing software with these standards and follow similar concepts yet my writeup will be successful if anyone finds it useful.</p><p>Let’s start ..</p><p><strong>1 . Use Clean Architecture:</strong> Nowadays, every programmer must use Clean Architecture when they write a program. Just not for themselves, this architecture will help his/her pair programmers or someone who needs your program to modify later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*B7LkQDyDqLN3rRSrNYkETA.jpeg" /><figcaption>Uncle Bob — Clean Architecture</figcaption></figure><p><strong>2. Know your stand:</strong> Just because someone using some different coding styles or tools they prefer, does not mean you need to use that too. If that is the standard or preferred, only then you may proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*NgcziNdu5xst8Xxz606-ag.png" /><figcaption>Collected from Web</figcaption></figure><p>Before proceeding, try to understand deeply how things work and how it is going to help you after implementing, what’s the impact on your project and how difficult it would be for the time allocated to deliver.</p><p>Sometimes, time becomes a big factor while trying to implement new things. Once one of my favorite teachers said, “Anyone can solve any problem given an infinite amount of time”. So we must consider the timeframe.</p><p><strong>3. Community is powerhouse: </strong>Be careful when using StackOverflow or any other community when you are seeking an answer for something. There are plenty of solutions available for a single problem. People solve it differently. Verify and use the authentic answer or recommended one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRLJsxaCYS3Dq-Lm_d3J0A.png" /><figcaption>source: stackoverflow.com</figcaption></figure><p><strong>4. Documentation is an asset: </strong>Create proper documentation of the codes you write. It’s a common trait, you will forget what you did last year. This documentation will also help your co-workers or others to understand what is the behavior of the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a99ecae0e66a4e0f435243244a0a4664/href">https://medium.com/media/a99ecae0e66a4e0f435243244a0a4664/href</a></iframe><p><strong>5. Train others: </strong>Sometimes we work in a team, it’s better to code what everyone understands. Either train each other to come into a common understanding or code like others can grasp it without any or minimum extra effort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNtS10A8XeKqpT_iweMr7w.jpeg" /></figure><p><strong>6. Choose language wisely:</strong> As I am an Android Developer, let me give you an example from that platform. When I started developing applications for the Android platform, I worked with Java. Later, Google made Kotlin their official language. Suddenly, the hype shifted to develop app with Kotlin instead of Java. I also joined the hype, and found in some communities, few people gave their reason why they want to stick with Java which obviously made me curious. I started comparing two languages and came to a point on which project language do I need to use and why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*etBPqCAEngmMZXaXbhaIwA.jpeg" /><figcaption>Collected from Web</figcaption></figure><p><strong>7. Respect Standards: </strong>Do not mess up with multiple languages. It is a very common trait among programmers that they want to learn multiple programming languages/platforms at a time, try to compare with each other and make the learning difficult and end up messing up things. Every platform or language have their own specific way of learning and following. Try to follow as the experts suggest.</p><p><strong>8. Unit testing is a must: </strong>Just because your program runs, does not mean that is full proof. Learn testing and implement it after every feature you implement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3zbFjotQc3tqArQj6ngyA.jpeg" /><figcaption>Collected from Web</figcaption></figure><p><strong>9. Reading is important: </strong>Read a lot of samples, codes written by different people to understand deeply. Start a positive conversation if you are confident enough to argue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*LiTkszLRDG46Sd_9R8Z2OQ.jpeg" /><figcaption>Collected from Web</figcaption></figure><p><strong>10. Go Open Source: </strong>Last but not least if you can make something different or helpful for your problem. Share with other people so that they also solve their problems. I personally have received a lot of support from other communities, friends, colleagues and others. I feel I have some responsibility towards them as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f2f6847e4e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2 . Practical example of State and Strategy Design Pattern (Android)]]></title>
            <link>https://nsaveek.medium.com/2-practical-example-of-state-and-strategy-design-pattern-android-874de1fba0d?source=rss-2cb605fc4602------2</link>
            <guid isPermaLink="false">https://medium.com/p/874de1fba0d</guid>
            <category><![CDATA[strategy-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Nasrat Sharif Aveek]]></dc:creator>
            <pubDate>Wed, 06 Mar 2019 15:21:04 GMT</pubDate>
            <atom:updated>2020-06-02T17:03:36.693Z</atom:updated>
            <content:encoded><![CDATA[<h3>2 . Practical example of State and Strategy Design Pattern (Android)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ZC2k8IM2isXBpd79dvkaCw.jpeg" /></figure><h3>Strategy Design Pattern :</h3><p>Here are some key points to implement <strong><em>Strategy</em></strong></p><ul><li>Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.</li><li>Capture the abstraction in an interface, bury implementation details in derived classes.</li></ul><p>Mainly strategy design pattern takes place when you need to implement different behaviour or plan (on large impact context). In Android, I have used this pattern for a set of data. For instance, let’s say you need to show different types of data inside list(RecyclerView) but based on different cases, the same item content will have different style or approach of showing. To be precise, let’s consider we have 3 TextViews, 1 Button, 1 ImageView inside one item of RecyclerView. Based on different conditions, The color of the TextViews will be different, the Button color and text will be different, the Image will be changed. We can handle this manually but… here is the Design Pattern to rescue you from having too many if, else or complex codebase to accomplish this. In this current world of programming this is totally discouraged to do this due to several reasons.</p><p>First, debugging later. If you need to debug your code later, that will be very difficult to handle if you have multiple strategies with complex behaviour.</p><p>Second, adding more cases. If you really need to add more cases, your code will fail no wonder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/096d6931afd77169700c9a81d87f85b8/href">https://medium.com/media/096d6931afd77169700c9a81d87f85b8/href</a></iframe><p>The example I have attached above have 3 different Strategies, each are unique in behaviour but applied on the same field. We just choose which strategy to pick based on the result (check : Strategy.kt). Let’s summarise the behaviour of the Strategies below.</p><ol><li>Each of the Strategy class (StrategyClasses.kt) have one common value to enable or disable the strategy implemented by the Interface IBaseStrategy(BaseStrategy.kt).</li><li>Each of the strategy classes (StrategyClasses.kt) have same fields with different values (i.e : primaryTextColor) and some unique value implemented by their own unique Interface.</li></ol><p>I believe the explanation above will help you to deal with complex requirements with a simple and easy solution.</p><p>N.B : As I previously mentioned, I am highly motivated by <a href="https://sourcemaking.com/">Source Making</a> for their awesome explanation of the Design Patterns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=874de1fba0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical example of State and Strategy Design Pattern (Android)]]></title>
            <link>https://nsaveek.medium.com/practical-example-of-stats-and-strategies-design-pattern-android-8d6df81b8ecc?source=rss-2cb605fc4602------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d6df81b8ecc</guid>
            <category><![CDATA[behavioural-design]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[state-design-pattern]]></category>
            <dc:creator><![CDATA[Nasrat Sharif Aveek]]></dc:creator>
            <pubDate>Sat, 02 Mar 2019 17:08:00 GMT</pubDate>
            <atom:updated>2020-06-03T04:08:35.849Z</atom:updated>
            <content:encoded><![CDATA[<p>As we all know, there are 3 different types of design patterns. Creational, Behavioural and Structural. Today, I am going to give some practical implementations of these two design patterns which are under <strong>Behavioural Design Pattern </strong>as it sounds confusing to many people. I believe, my understanding and implementation can help people to understand to minimum level at least. Like always, I appreciate positive feedback, comments and suggestions as I regularly improve myself by learning.</p><p>Think about a case when the application/ software needs to change its behaviour dynamically. For instance, if I give an example from Android development; one of the most common behaviours of recycler view is multiple view inside one single recycler view. We need to change the view runtime and show the correspondent view to the users. We can implement <strong>“State”</strong> design pattern to decide which view to load and when.</p><p><strong>“Strategy”</strong> pattern is more like the idea or plan we set in order to execute to accomplish something. In real life, you can consider a defence force prepares Strategy for a war. Everyone has a different war strategy and all of the participants want to see their strategies effective.</p><h3>State Design Pattern :</h3><p>Here are some key points to implement this design pattern..</p><ul><li>A <strong><em>context</em></strong> class to represent a gateway/interface to all.</li><li>A <strong>base</strong> class or interface.</li><li>Different <strong>states</strong> of the object as classes of the State base class/interface.</li><li>Different behaviour for different States derived classes/interfaces.</li></ul><p>I am going to share one practical example when I had to use State Design Pattern in my project. The project I was working on, had different behaviour for different countries to show data inside a list. For instance, the api response was supposed to give <strong><em>dataset A</em></strong> under flag <strong><em>“X” </em></strong>for Country <strong><em>C </em></strong>and <strong><em>dataset B</em></strong> under the same flag for Country <strong><em>D. </em></strong>So, it was pretty clear that the <strong>Country</strong> was the <strong>State changing factor </strong>in this case.</p><p>Since I have shown these data on a list (Recycler View), As you know we need to define Viewholder and implement <strong>Adapter design pattern.</strong></p><p>First see the structure that I have attached below to understand the architecture more clearly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*qzVNt_F3F35ghHLmC1-_PQ.png" /><figcaption>Flow of states</figcaption></figure><p>To us, StateViewHolder class is the Base Class..</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bbfd701d090323cc41a8d88fd77bbc7/href">https://medium.com/media/5bbfd701d090323cc41a8d88fd77bbc7/href</a></iframe><p>Let’s look at the BaseContext class and other interfaces..</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b710b572490de0b4be07b21b377eb386/href">https://medium.com/media/b710b572490de0b4be07b21b377eb386/href</a></iframe><p>the classes responsible for handling the states..</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c29c0e0d7ac7ee35bf26ae2ccdb9f53/href">https://medium.com/media/0c29c0e0d7ac7ee35bf26ae2ccdb9f53/href</a></iframe><p>I believe the diagram makes a bit more clear sense if you look at the code examples. Also, in the <a href="https://medium.com/p/874de1fba0d/edit"><strong>second</strong></a> part, I will be discussing the Strategy design pattern with example. Until then, good bye :)</p><p>N.B: I was highly inspired from <a href="https://sourcemaking.com/"><strong><em>Source Making</em></strong></a> for their awesome explanation of each design patterns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d6df81b8ecc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Repository pattern in Android]]></title>
            <link>https://nsaveek.medium.com/repository-pattern-in-android-e6ebbc16595f?source=rss-2cb605fc4602------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6ebbc16595f</guid>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[realm]]></category>
            <dc:creator><![CDATA[Nasrat Sharif Aveek]]></dc:creator>
            <pubDate>Fri, 12 Oct 2018 04:57:45 GMT</pubDate>
            <atom:updated>2020-06-02T17:05:01.873Z</atom:updated>
            <content:encoded><![CDATA[<p>Once upon a time there was a king.. Lol. No, I am not going to share any story today instead I will be focusing on another important topic for the programmers; The <strong>Repository</strong> pattern. I only share things that I feel is needed to share which I have learnt by passing difficult times and have learnt successfully, what I can explain more clear and concise way so that people can understand easily. I believe before riding motorbikes, everyone must know how to ride bicycles so that their foundation gets strong.</p><p>Since the first month of my professional career in Android, I have been using the database either with sqlite or other. I was using the same code again and again using <strong>DAO</strong> pattern and never questioned why would I use that.</p><p>Later, as I grow experienced more and more, I started asking myself is there any better approach that can help me to reduce the effort/boilerplate code which can make my productivity increased and faster? Database is the easiest choice for me to have RnD. And guess what, I have found the Repository pattern quite useful and here I am going to explain what is <strong><em>repository pattern</em></strong>, <strong><em>how can we implement in our codebase</em></strong> and of course <strong><em>how does it help us</em></strong>.</p><p>Simply, a Repository pattern is such pattern where the business will ask for receipt and won’t know how the price is getting calculated and printed on the receipt.</p><p>We will take the database example with <strong>realm</strong> on Android</p><p>We will have one <strong>IRepository</strong> which will contain all the necessary methods to build a repository class and one <strong>DatabaseRepository</strong> class which will implement the <strong>IRepository</strong> and modify the return values.</p><h3>Let’s create that..</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8933e39eaf0be0e1dbe6b8f6a19c8ca/href">https://medium.com/media/b8933e39eaf0be0e1dbe6b8f6a19c8ca/href</a></iframe><p>Now let’s see how we can implement the Interface in our class..</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88f74f84aa72a53b1f05e9362e6f0549/href">https://medium.com/media/88f74f84aa72a53b1f05e9362e6f0549/href</a></iframe><p>So the class is ready. Let’s use it in our project now.</p><pre>class MainActivity : AppCompatActivity() {</pre><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    setContentView(R.layout.<em>activity_main</em>)<br><br>    val databaseRepository = DatabaseRepository()<br><br><br>    val student  = <br>    Student.StudentBuilder(&quot;Aveek&quot;,&quot;Dhaka,Bangladesh&quot;,<br>    &quot;aveek@email.com&quot;).create()<br><br>    Log.d(&quot;Student is &quot;, student.toString())<br><br>    val dataStored = databaseRepository.saveStudentData(student);<br><br>    if (dataStored){<br>        Toast.makeText(this,&quot;data has been saved<br>        successfully&quot;,Toast.<em>LENGTH_LONG</em>).show()<br>    }<br>}<br>}</pre><p>For the description purpose, I only have added the saveData function. You can use the remaining functions in your project.</p><p>Get the full code in the <strong><em>github</em></strong> project below</p><p><a href="https://github.com/NsAveek/DesignPatterns/tree/repository">NsAveek/DesignPatterns</a></p><p>In the realm browser, it will look like this..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZASYUwVP5FjC_kIEHkr9vA.png" /></figure><p>If you want to see the stored data, you can have a look at my answer at SO</p><p><a href="https://stackoverflow.com/a/44184531/963400">How do I view my Realm file in the Realm Browser?</a></p><p>You can create as many interfaces as you want to get your requirements done. Also, you can implement the same interface in multiple classes to achieve your requirement. For instance, you can have a <strong>Local Database</strong> class which will store the data to local storage and one <strong>Remote Database</strong> class which will store data to somewhere else. In both cases you can implement the same <strong>IStoreRepository</strong> interface to achieve the outcome. On the other hand, your Database class can implement multiple Interface to communicate with two different storage option.</p><blockquote><em>Checkout the Builder design pattern if you are interested..</em></blockquote><p><a href="https://medium.com/@nsaveek/builder-design-pattern-in-android-ab764e76f94">Builder Design Pattern in Android</a></p><p>Keep exploring and I am open to get the feedback on my writings. I would love to hear any update, positive feedback or suggestions to improve my understanding and writing.</p><p>Cheerio.. :) :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6ebbc16595f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Builder Design Pattern in Android]]></title>
            <link>https://nsaveek.medium.com/builder-design-pattern-in-android-ab764e76f94?source=rss-2cb605fc4602------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab764e76f94</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nasrat Sharif Aveek]]></dc:creator>
            <pubDate>Wed, 12 Sep 2018 09:47:21 GMT</pubDate>
            <atom:updated>2018-10-16T08:37:25.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAb8DGMre0e6iquM2pW8hQ.png" /></figure><p>Good day folks! Today I am going to share the same tea in a new pot; Builder design pattern in Android app development with real use case example in a project and implementation.</p><p>Builder design pattern is one of <strong>Creational</strong> Design Patterns available. As we already know, there are 3 different categories of dp’s.</p><ol><li><strong>Creational</strong></li><li><strong>Behavioral</strong></li><li><strong>Structural</strong></li></ol><p>In brief, Builder design pattern helps creation of an object in a more readable and cleanable way. From the quotes of <strong><em>Gang of four</em></strong> -</p><blockquote>“Separate the construction of a complex object from its representation so that the same construction process can create different representations.”</blockquote><p>Mostly, it is helpful when you have an object with different types of parameters involved. Meaning to say, let’s say you have an object with 5 fields, 3 is a must to create the object and the rest 2 are optional. You have to pass the mandatory 3 fields in the constructor to create the object and the optional 2 you can use or can ignore. To understand more, let’s take an example from the AlertDialog class from Android.</p><pre>val alertDialog : AlertDialog<strong> = </strong>AlertDialog.Builder(<strong>this</strong>)<br>        .setTitle(&quot;Builder Example&quot;)<br>        .setMessage(&quot;Builder implementation in Alert Dialog&quot;)<br>        .create();</pre><p>In the above example, you can see this class takes the Context as the mandatory parameter and the remaining ( setTitle and setMessage) are optional.</p><h3><strong>The Benefits in a nutshell</strong></h3><p>First, I will be going through a real use case then will discuss the usefulness of Builder pattern.</p><blockquote>Consider one registration form where one <strong>Student</strong> or <strong>User</strong> or <strong>Person</strong> needs to fill up his/her details. You must have noticed, there are fields which are mandatory marked with *(asterisk) the remaining are optional. For instance, the <strong>name</strong>, <strong>address</strong> and <strong>email</strong> are mandatory. <strong>Mobile phone number</strong>, <strong>passport number</strong> and <strong>age</strong> are optional.</blockquote><ol><li>If you would do the same task without builder just like I used to do once, you would create different parameters for creating the object.</li></ol><pre>public class Student {<br>    String name;<br>    String address;<br>    String email;<br>    String phoneNumber;<br>    String passportNumber;<br>    int age;<br><br>    Student(String name, String address, String email) {<br>        this.name = name;<br>        this.address = address;<br>        this.email = email;<br>    }<br><br>    Student(String name, String address, String email, String phoneNumber) {<br>        this.name = name;<br>        this.address = address;<br>        this.email = email;<br>        this.phoneNumber = phoneNumber;<br>    }<br><br>    Student(String name, String address, String email, String phoneNumber, String passportNumber) {<br>        this.name = name;<br>        this.address = address;<br>        this.email = email;<br>        this.phoneNumber = phoneNumber;<br>        this.passportNumber = passportNumber;<br>    }<br><br>    Student(String name, String address, String email, String phoneNumber, String passportNumber, int age) {<br>        this.name = name;<br>        this.address = address;<br>        this.email = email;<br>        this.phoneNumber = phoneNumber;<br>        this.passportNumber = passportNumber;<br>        this.age = age;<br>    }<br>}</pre><p>or</p><pre>class Student{</pre><pre>   val name : String<br>   val address : String<br>   val email : String<br>   val phoneNumber : String<br>   val passportNumber : String<br>   val age : Int</pre><pre>   Student(name, address, email, phoneNumber, passportNumber, age){<br>    this.name = name<br>    this.address = address<br>    this.email = email<br>    this.phoneNumber = phoneNumber<br>    this.passportNumber = passportNumber<br>    this.age = age<br>   }<br>}</pre><p>where you would pass null or empty values to the constructor and make it FAT.</p><p>As a programmer, for the sake of programming, these are not an expected approach to design any object. Why? Because, firstly this fails the general rules of creation of an object, “Make it simple”. Secondly, if you run Unit Test, it would be a mess and difficult to handle the test cases.</p><p>2. With a builder</p><pre>val student  = Student.StudentBuilder(&quot;Aveek&quot;,&quot;Dhaka, Bangladesh&quot;,&quot;aveek@email.com&quot;)<br>        .setPassportNumber(&quot;RRT098234&quot;)<br>        .create()</pre><p>or</p><pre>val student  = Student.StudentBuilder(&quot;Max&quot;,&quot;Jakarta, Indonesia&quot;,&quot;max@email.com&quot;)<br>        .setAge(30)<br>        .setPhoneNumber(&quot;+08722348234&quot;)<br>        .create()</pre><p>Look at the differences, we have successfully achieved what we need but in a more clean and readable way. Later, if we need any more parameter we can achieve this easily.</p><h3><strong>How do we create a Builder ?</strong></h3><p>Okay, now we have understood the benefits and it is time to see how actually we can create a builder class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce3f763e55ccce638993878af6440a75/href">https://medium.com/media/ce3f763e55ccce638993878af6440a75/href</a></iframe><p>Look at the complete example at <a href="https://github.com/NsAveek/DesignPatterns/tree/builder">Github</a>. Also, look at the Repository pattern I wrote..</p><p><a href="https://medium.com/@nsaveek/repository-pattern-in-android-e6ebbc16595f">Repository pattern in Android</a></p><p>Thanks for reading.. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab764e76f94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Lambda Expression (Part 1 ~ Java)]]></title>
            <link>https://nsaveek.medium.com/mastering-lambda-expression-part-1-java-b82d67488e68?source=rss-2cb605fc4602------2</link>
            <guid isPermaLink="false">https://medium.com/p/b82d67488e68</guid>
            <category><![CDATA[lambda-expressions]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nasrat Sharif Aveek]]></dc:creator>
            <pubDate>Sun, 26 Aug 2018 15:20:44 GMT</pubDate>
            <atom:updated>2018-08-26T16:17:32.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bycboZPO0GifDYay8_8hig.png" /></figure><blockquote>Scare Nothing, take chance !! You either win or you will learn!</blockquote><p>Lambda! A great way to write code in a short but more readable way efficiently. Once you feel comfortable with Lambda Expression, I am pretty sure you will start using it every possible place you can!</p><p>This has become popular in recent days. Specially in Java/Kotlin. In Java 8, you can start using the lambda expression in your application.</p><p>Let’s start learning it</p><p>Before starting learning it, I need to tell some rules of thumb regarding the implementation of lambda.</p><ol><li>You only can implement Lambda on abstraction, Mostly on interfaces.</li><li>The interface can only contain one abstract method which you can convert to lambda.</li></ol><p>A good example can be the OnClickListener of the View class. If we look at the implementation, we can see</p><pre>View.OnClickListener clickListener = new View.OnClickListener() {<br>    @Override<br>    public void onClick(View view) {<br>        Log.<em>d</em>(&quot;clickTest&quot;, &quot;onClick clicked&quot;);<br>    }<br>};</pre><p>If we look at the View class, we can see the OnClickListener interface have only one method “onClick”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qczGG_hnnoAgWHbUW8fQJw.png" /></figure><p>Now we will see how we can convert the implementation into lambda.</p><pre>View.OnClickListener clickListener = (view) -&gt; { Log.<em>d</em>(&quot;clickTest&quot;, &quot;onClick clicked&quot;);};</pre><p>Let’s explain a bit more..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lqa2O73zJqpklrxjNeKqxg.png" /></figure><p>The red marked part is the onClick method <strong>parameter</strong> whereas the green marked area is the <strong>action</strong> once the onClick method gets called.</p><p>We can simplify more. If we have only action to be done once onClick gets called, then we can remove the curly braces after “ -&gt; ”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81ExdJnrkLcQC9Bzf1U4eA.png" /></figure><p>else</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFhte4I4lK1zs9NHQ084Ww.png" /></figure><p>Now what if there are two parameters in the method? For instance, look at the interface below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eBSnmg-Vp7S5UaiHvcI6LQ.png" /></figure><p>Let’s see it with elaborated version first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Na9oNn6QoYHeC0kQc45_MA.png" /></figure><p>After converted to lambda</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9TL980HsBGVLBSbPoc62Q.png" /></figure><p>The last two things, What if the method returns some value and the method without any parameter?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zePK68Ef1A4bkEG5b2udfA.png" /></figure><p>And the lambda..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-tY-mly2JbWUC1DNYlthQ.png" /></figure><p>let’s remove more lines..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SLr4_hcGzyV3GcPz3hYiQg.png" /><figcaption>No need to write return</figcaption></figure><p>I believe, I have made the confusions cleared. If you still confused, reply in the comment. I will try to get back asap.</p><p>Thank you for reading.. stay connected :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b82d67488e68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>